deprecate BaseCommand
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 · parent f5e47a6 · Browse files · 6 files·+323 added−350 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+323 added−350 removed
- tests:+2 added−2 removed
- other:+321 added−348 removed
Provenance
- Commit
9dd1207- Tree
22888b6- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
f5e47a6
6 files changed+323 added−350 removed
modified:src/click/__init__.py+17 added-1 removed
3 unmodified lines4 around a simple API that does not come with too much magic and is5 composable.6 """7 from .core import Argument as Argument8-from .core import BaseCommand as BaseCommand8 from .core import Command as Command9 from .core import CommandCollection as CommandCollection10 from .core import Context as Context11 from .core import Group as Group57 unmodified lines69 from .utils import get_text_stream as get_text_stream70 from .utils import open_file as open_file71 72 __version__ = "8.2.0.dev0"73+74+75+def __getattr__(name: str) -> object:76+ import warnings77+78+ if name == "BaseCommand":79+ from .core import _BaseCommand80+81+ warnings.warn(82+ "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"83+ " 'Command' instead.",84+ DeprecationWarning,85+ stacklevel=2,86+ )87+ return _BaseCommand88+89+ raise AttributeError(name)modified:src/click/core.py+294 added-339 removed
829 unmodified lines830 """831 return self._parameter_source.get(name)832 833 834-class BaseCommand:835- """The base command implements the minimal API contract of commands.836- Most code will never use this as it does not implement a lot of useful837- functionality but it can act as the direct subclass of alternative838- parsing methods that do not depend on the Click parser.839-840- For instance, this can be used to bridge Click and other systems like841- argparse or docopt.842-843- Because base commands do not implement a lot of the API that other844- parts of Click take for granted, they are not supported for all845- operations. For instance, they cannot be used with the decorators846- usually and they have no built-in callback system.847-848- .. versionchanged:: 2.0849- Added the `context_settings` parameter.850-851- :param name: the name of the command to use unless a group overrides it.852- :param context_settings: an optional dictionary with defaults that are853- passed to the context object.854- """855-856- #: The context class to create with :meth:`make_context`.857- #:858- #: .. versionadded:: 8.0859- context_class: t.Type[Context] = Context860- #: the default for the :attr:`Context.allow_extra_args` flag.861- allow_extra_args = False862- #: the default for the :attr:`Context.allow_interspersed_args` flag.863- allow_interspersed_args = True864- #: the default for the :attr:`Context.ignore_unknown_options` flag.865- ignore_unknown_options = False866-867- def __init__(868- self,869- name: t.Optional[str],870- context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,871- ) -> None:872- #: the name the command thinks it has. Upon registering a command873- #: on a :class:`Group` the group will default the command name874- #: with this information. You should instead use the875- #: :class:`Context`\'s :attr:`~Context.info_name` attribute.876- self.name = name877-878- if context_settings is None:879- context_settings = {}880-881- #: an optional dictionary with defaults passed to the context.882- self.context_settings: t.MutableMapping[str, t.Any] = context_settings883-884- def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:885- """Gather information that could be useful for a tool generating886- user-facing documentation. This traverses the entire structure887- below this command.888-889- Use :meth:`click.Context.to_info_dict` to traverse the entire890- CLI structure.891-892- :param ctx: A :class:`Context` representing this command.893-894- .. versionadded:: 8.0895- """896- return {"name": self.name}897-898- def __repr__(self) -> str:899- return f"<{self.__class__.__name__} {self.name}>"900-901- def get_usage(self, ctx: Context) -> str:902- raise NotImplementedError("Base commands cannot get usage")903-904- def get_help(self, ctx: Context) -> str:905- raise NotImplementedError("Base commands cannot get help")906-907- def make_context(908- self,909- info_name: t.Optional[str],910- args: t.List[str],911- parent: t.Optional[Context] = None,912- **extra: t.Any,913- ) -> Context:914- """This function when given an info name and arguments will kick915- off the parsing and create a new :class:`Context`. It does not916- invoke the actual command callback though.917-918- To quickly customize the context class used without overriding919- this method, set the :attr:`context_class` attribute.920-921- :param info_name: the info name for this invocation. Generally this922- is the most descriptive name for the script or923- command. For the toplevel script it's usually924- the name of the script, for commands below it's925- the name of the command.926- :param args: the arguments to parse as list of strings.927- :param parent: the parent context if available.928- :param extra: extra keyword arguments forwarded to the context929- constructor.930-931- .. versionchanged:: 8.0932- Added the :attr:`context_class` attribute.933- """934- for key, value in self.context_settings.items():935- if key not in extra:936- extra[key] = value937-938- ctx = self.context_class(939- self, info_name=info_name, parent=parent, **extra # type: ignore940- )941-942- with ctx.scope(cleanup=False):943- self.parse_args(ctx, args)944- return ctx945-946- def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:947- """Given a context and a list of arguments this creates the parser948- and parses the arguments, then modifies the context as necessary.949- This is automatically invoked by :meth:`make_context`.950- """951- raise NotImplementedError("Base commands do not know how to parse arguments.")952-953- def invoke(self, ctx: Context) -> t.Any:954- """Given a context, this invokes the command. The default955- implementation is raising a not implemented error.956- """957- raise NotImplementedError("Base commands are not invocable by default")958-959- def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:960- """Return a list of completions for the incomplete value. Looks961- at the names of chained multi-commands.962-963- Any command could be part of a chained multi-command, so sibling964- commands are valid at any point during command completion. Other965- command classes will return more completions.966-967- :param ctx: Invocation context for this command.968- :param incomplete: Value being completed. May be empty.969-970- .. versionadded:: 8.0971- """972- from click.shell_completion import CompletionItem973-974- results: t.List["CompletionItem"] = []975-976- while ctx.parent is not None:977- ctx = ctx.parent978-979- if isinstance(ctx.command, MultiCommand) and ctx.command.chain:980- results.extend(981- CompletionItem(name, help=command.get_short_help_str())982- for name, command in _complete_visible_commands(ctx, incomplete)983- if name not in ctx.protected_args984- )985-986- return results987-988- @t.overload989- def main(990- self,991- args: t.Optional[t.Sequence[str]] = None,992- prog_name: t.Optional[str] = None,993- complete_var: t.Optional[str] = None,994- standalone_mode: "te.Literal[True]" = True,995- **extra: t.Any,996- ) -> "te.NoReturn":997- ...998-999- @t.overload1000- def main(1001- self,1002- args: t.Optional[t.Sequence[str]] = None,1003- prog_name: t.Optional[str] = None,1004- complete_var: t.Optional[str] = None,1005- standalone_mode: bool = ...,1006- **extra: t.Any,1007- ) -> t.Any:1008- ...1009-1010- def main(1011- self,1012- args: t.Optional[t.Sequence[str]] = None,1013- prog_name: t.Optional[str] = None,1014- complete_var: t.Optional[str] = None,1015- standalone_mode: bool = True,1016- windows_expand_args: bool = True,1017- **extra: t.Any,1018- ) -> t.Any:1019- """This is the way to invoke a script with all the bells and1020- whistles as a command line application. This will always terminate1021- the application after a call. If this is not wanted, ``SystemExit``1022- needs to be caught.1023-1024- This method is also available by directly calling the instance of1025- a :class:`Command`.1026-1027- :param args: the arguments that should be used for parsing. If not1028- provided, ``sys.argv[1:]`` is used.1029- :param prog_name: the program name that should be used. By default1030- the program name is constructed by taking the file1031- name from ``sys.argv[0]``.1032- :param complete_var: the environment variable that controls the1033- bash completion support. The default is1034- ``"_<prog_name>_COMPLETE"`` with prog_name in1035- uppercase.1036- :param standalone_mode: the default behavior is to invoke the script1037- in standalone mode. Click will then1038- handle exceptions and convert them into1039- error messages and the function will never1040- return but shut down the interpreter. If1041- this is set to `False` they will be1042- propagated to the caller and the return1043- value of this function is the return value1044- of :meth:`invoke`.1045- :param windows_expand_args: Expand glob patterns, user dir, and1046- env vars in command line args on Windows.1047- :param extra: extra keyword arguments are forwarded to the context1048- constructor. See :class:`Context` for more information.1049-1050- .. versionchanged:: 8.0.11051- Added the ``windows_expand_args`` parameter to allow1052- disabling command line arg expansion on Windows.1053-1054- .. versionchanged:: 8.01055- When taking arguments from ``sys.argv`` on Windows, glob1056- patterns, user dir, and env vars are expanded.1057-1058- .. versionchanged:: 3.01059- Added the ``standalone_mode`` parameter.1060- """1061- if args is None:1062- args = sys.argv[1:]1063-1064- if os.name == "nt" and windows_expand_args:1065- args = _expand_args(args)1066- else:1067- args = list(args)1068-1069- if prog_name is None:1070- prog_name = _detect_program_name()1071-1072- # Process shell completion requests and exit early.1073- self._main_shell_completion(extra, prog_name, complete_var)1074-1075- try:1076- try:1077- with self.make_context(prog_name, args, **extra) as ctx:1078- rv = self.invoke(ctx)1079- if not standalone_mode:1080- return rv1081- # it's not safe to `ctx.exit(rv)` here!1082- # note that `rv` may actually contain data like "1" which1083- # has obvious effects1084- # more subtle case: `rv=[None, None]` can come out of1085- # chained commands which all returned `None` -- so it's not1086- # even always obvious that `rv` indicates success/failure1087- # by its truthiness/falsiness1088- ctx.exit()1089- except (EOFError, KeyboardInterrupt) as e:1090- echo(file=sys.stderr)1091- raise Abort() from e1092- except ClickException as e:1093- if not standalone_mode:1094- raise1095- e.show()1096- sys.exit(e.exit_code)1097- except OSError as e:1098- if e.errno == errno.EPIPE:1099- sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))1100- sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))1101- sys.exit(1)1102- else:1103- raise1104- except Exit as e:1105- if standalone_mode:1106- sys.exit(e.exit_code)1107- else:1108- # in non-standalone mode, return the exit code1109- # note that this is only reached if `self.invoke` above raises1110- # an Exit explicitly -- thus bypassing the check there which1111- # would return its result1112- # the results of non-standalone execution may therefore be1113- # somewhat ambiguous: if there are codepaths which lead to1114- # `ctx.exit(1)` and to `return 1`, the caller won't be able to1115- # tell the difference between the two1116- return e.exit_code1117- except Abort:1118- if not standalone_mode:1119- raise1120- echo(_("Aborted!"), file=sys.stderr)1121- sys.exit(1)1122-1123- def _main_shell_completion(1124- self,1125- ctx_args: t.MutableMapping[str, t.Any],1126- prog_name: str,1127- complete_var: t.Optional[str] = None,1128- ) -> None:1129- """Check if the shell is asking for tab completion, process1130- that, then exit early. Called from :meth:`main` before the1131- program is invoked.1132-1133- :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: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:1148- return1149-1150- from .shell_completion import shell_complete1151-1152- rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1153- sys.exit(rv)1154-1155- def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:1156- """Alias for :meth:`main`."""1157- return self.main(*args, **kwargs)1158-1159-1160-class Command(BaseCommand):834+class Command:835 """Commands are the basic building block of command line interfaces in836 Click. A basic command handles command line parsing and might dispatch837 more parsing to commands nested below it.838 18 unmodified lines857 858 :param deprecated: issues a message indicating that859 the command is deprecated.860 861+ .. versionchanged:: 8.2862+ This is the base class for all commands, not ``BaseCommand``.863+864 .. versionchanged:: 8.1865 ``help``, ``epilog``, and ``short_help`` are stored unprocessed,866 all formatting is done when outputting help text, not at init,867 and is done even if not using the ``@command`` decorator.7 unmodified lines875 .. versionchanged:: 2.0876 Added the ``context_settings`` parameter.877 """878 879+ #: The context class to create with :meth:`make_context`.880+ #:881+ #: .. versionadded:: 8.0882+ context_class: t.Type[Context] = Context883+884+ #: the default for the :attr:`Context.allow_extra_args` flag.885+ allow_extra_args = False886+887+ #: the default for the :attr:`Context.allow_interspersed_args` flag.888+ allow_interspersed_args = True889+890+ #: the default for the :attr:`Context.ignore_unknown_options` flag.891+ ignore_unknown_options = False892+893 def __init__(894 self,895 name: t.Optional[str],896 context_settings: t.Optional[t.MutableMapping[str, t.Any]] = None,7 unmodified lines904 no_args_is_help: bool = False,905 hidden: bool = False,906 deprecated: bool = False,907 ) -> None:1217- super().__init__(name, context_settings)908+ #: the name the command thinks it has. Upon registering a command909+ #: on a :class:`Group` the group will default the command name910+ #: with this information. You should instead use the911+ #: :class:`Context`\'s :attr:`~Context.info_name` attribute.912+ self.name = name913+914+ if context_settings is None:915+ context_settings = {}916+917+ #: an optional dictionary with defaults passed to the context.918+ self.context_settings: t.MutableMapping[str, t.Any] = context_settings919+920 #: the callback to execute when the command fires. This might be921 #: `None` in which case nothing happens.922 self.callback = callback923 #: the list of parameters for this command in the order they9 unmodified lines933 self.hidden = hidden934 self.deprecated = deprecated935 936 def to_info_dict(self, ctx: Context) -> t.Dict[str, t.Any]:1235- info_dict = super().to_info_dict(ctx)1236- info_dict.update(1237- params=[param.to_info_dict() for param in self.get_params(ctx)],1238- help=self.help,1239- epilog=self.epilog,1240- short_help=self.short_help,1241- hidden=self.hidden,1242- deprecated=self.deprecated,1243- )1244- return info_dict937+ return {938+ "name": self.name,939+ "params": [param.to_info_dict() for param in self.get_params(ctx)],940+ "help": self.help,941+ "epilog": self.epilog,942+ "short_help": self.short_help,943+ "hidden": self.hidden,944+ "deprecated": self.deprecated,945+ }946 947+ def __repr__(self) -> str:948+ return f"<{self.__class__.__name__} {self.name}>"949+950 def get_usage(self, ctx: Context) -> str:951 """Formats the usage line into a string and returns it.952 953 Calls :meth:`format_usage` internally.145 unmodified lines1099 1100 with formatter.indentation():1101 formatter.write_text(epilog)1102 1103+ def make_context(1104+ self,1105+ info_name: t.Optional[str],1106+ args: t.List[str],1107+ parent: t.Optional[Context] = None,1108+ **extra: t.Any,1109+ ) -> Context:1110+ """This function when given an info name and arguments will kick1111+ off the parsing and create a new :class:`Context`. It does not1112+ invoke the actual command callback though.1113+1114+ To quickly customize the context class used without overriding1115+ this method, set the :attr:`context_class` attribute.1116+1117+ :param info_name: the info name for this invocation. Generally this1118+ is the most descriptive name for the script or1119+ command. For the toplevel script it's usually1120+ the name of the script, for commands below it's1121+ the name of the command.1122+ :param args: the arguments to parse as list of strings.1123+ :param parent: the parent context if available.1124+ :param extra: extra keyword arguments forwarded to the context1125+ constructor.1126+1127+ .. versionchanged:: 8.01128+ Added the :attr:`context_class` attribute.1129+ """1130+ for key, value in self.context_settings.items():1131+ if key not in extra:1132+ extra[key] = value1133+1134+ ctx = self.context_class(self, info_name=info_name, parent=parent, **extra)1135+1136+ with ctx.scope(cleanup=False):1137+ self.parse_args(ctx, args)1138+ return ctx1139+1140 def parse_args(self, ctx: Context, args: t.List[str]) -> t.List[str]:1141 if not args and self.no_args_is_help and not ctx.resilient_parsing:1142 echo(ctx.get_help(), color=ctx.color)1143 ctx.exit()33 unmodified lines1177 def shell_complete(self, ctx: Context, incomplete: str) -> t.List["CompletionItem"]:1178 """Return a list of completions for the incomplete value. Looks1179 at the names of options and chained multi-commands.1180 1181+ Any command could be part of a chained multi-command, so sibling1182+ commands are valid at any point during command completion.1183+1184 :param ctx: Invocation context for this command.1185 :param incomplete: Value being completed. May be empty.1186 1187 .. versionadded:: 8.020 unmodified lines1208 for name in [*param.opts, *param.secondary_opts]1209 if name.startswith(incomplete)1210 )1211 1468- results.extend(super().shell_complete(ctx, incomplete))1212+ while ctx.parent is not None:1213+ ctx = ctx.parent1214+1215+ if isinstance(ctx.command, MultiCommand) and ctx.command.chain:1216+ results.extend(1217+ CompletionItem(name, help=command.get_short_help_str())1218+ for name, command in _complete_visible_commands(ctx, incomplete)1219+ if name not in ctx.protected_args1220+ )1221+1222 return results1223 1224+ @t.overload1225+ def main(1226+ self,1227+ args: t.Optional[t.Sequence[str]] = None,1228+ prog_name: t.Optional[str] = None,1229+ complete_var: t.Optional[str] = None,1230+ standalone_mode: "te.Literal[True]" = True,1231+ **extra: t.Any,1232+ ) -> "te.NoReturn":1233+ ...1234 1235+ @t.overload1236+ def main(1237+ self,1238+ args: t.Optional[t.Sequence[str]] = None,1239+ prog_name: t.Optional[str] = None,1240+ complete_var: t.Optional[str] = None,1241+ standalone_mode: bool = ...,1242+ **extra: t.Any,1243+ ) -> t.Any:1244+ ...1245+1246+ def main(1247+ self,1248+ args: t.Optional[t.Sequence[str]] = None,1249+ prog_name: t.Optional[str] = None,1250+ complete_var: t.Optional[str] = None,1251+ standalone_mode: bool = True,1252+ windows_expand_args: bool = True,1253+ **extra: t.Any,1254+ ) -> t.Any:1255+ """This is the way to invoke a script with all the bells and1256+ whistles as a command line application. This will always terminate1257+ the application after a call. If this is not wanted, ``SystemExit``1258+ needs to be caught.1259+1260+ This method is also available by directly calling the instance of1261+ a :class:`Command`.1262+1263+ :param args: the arguments that should be used for parsing. If not1264+ provided, ``sys.argv[1:]`` is used.1265+ :param prog_name: the program name that should be used. By default1266+ the program name is constructed by taking the file1267+ name from ``sys.argv[0]``.1268+ :param complete_var: the environment variable that controls the1269+ bash completion support. The default is1270+ ``"_<prog_name>_COMPLETE"`` with prog_name in1271+ uppercase.1272+ :param standalone_mode: the default behavior is to invoke the script1273+ in standalone mode. Click will then1274+ handle exceptions and convert them into1275+ error messages and the function will never1276+ return but shut down the interpreter. If1277+ this is set to `False` they will be1278+ propagated to the caller and the return1279+ value of this function is the return value1280+ of :meth:`invoke`.1281+ :param windows_expand_args: Expand glob patterns, user dir, and1282+ env vars in command line args on Windows.1283+ :param extra: extra keyword arguments are forwarded to the context1284+ constructor. See :class:`Context` for more information.1285+1286+ .. versionchanged:: 8.0.11287+ Added the ``windows_expand_args`` parameter to allow1288+ disabling command line arg expansion on Windows.1289+1290+ .. versionchanged:: 8.01291+ When taking arguments from ``sys.argv`` on Windows, glob1292+ patterns, user dir, and env vars are expanded.1293+1294+ .. versionchanged:: 3.01295+ Added the ``standalone_mode`` parameter.1296+ """1297+ if args is None:1298+ args = sys.argv[1:]1299+1300+ if os.name == "nt" and windows_expand_args:1301+ args = _expand_args(args)1302+ else:1303+ args = list(args)1304+1305+ if prog_name is None:1306+ prog_name = _detect_program_name()1307+1308+ # Process shell completion requests and exit early.1309+ self._main_shell_completion(extra, prog_name, complete_var)1310+1311+ try:1312+ try:1313+ with self.make_context(prog_name, args, **extra) as ctx:1314+ rv = self.invoke(ctx)1315+ if not standalone_mode:1316+ return rv1317+ # it's not safe to `ctx.exit(rv)` here!1318+ # note that `rv` may actually contain data like "1" which1319+ # has obvious effects1320+ # more subtle case: `rv=[None, None]` can come out of1321+ # chained commands which all returned `None` -- so it's not1322+ # even always obvious that `rv` indicates success/failure1323+ # by its truthiness/falsiness1324+ ctx.exit()1325+ except (EOFError, KeyboardInterrupt) as e:1326+ echo(file=sys.stderr)1327+ raise Abort() from e1328+ except ClickException as e:1329+ if not standalone_mode:1330+ raise1331+ e.show()1332+ sys.exit(e.exit_code)1333+ except OSError as e:1334+ if e.errno == errno.EPIPE:1335+ sys.stdout = t.cast(t.TextIO, PacifyFlushWrapper(sys.stdout))1336+ sys.stderr = t.cast(t.TextIO, PacifyFlushWrapper(sys.stderr))1337+ sys.exit(1)1338+ else:1339+ raise1340+ except Exit as e:1341+ if standalone_mode:1342+ sys.exit(e.exit_code)1343+ else:1344+ # in non-standalone mode, return the exit code1345+ # note that this is only reached if `self.invoke` above raises1346+ # an Exit explicitly -- thus bypassing the check there which1347+ # would return its result1348+ # the results of non-standalone execution may therefore be1349+ # somewhat ambiguous: if there are codepaths which lead to1350+ # `ctx.exit(1)` and to `return 1`, the caller won't be able to1351+ # tell the difference between the two1352+ return e.exit_code1353+ except Abort:1354+ if not standalone_mode:1355+ raise1356+ echo(_("Aborted!"), file=sys.stderr)1357+ sys.exit(1)1358+1359+ def _main_shell_completion(1360+ self,1361+ ctx_args: t.MutableMapping[str, t.Any],1362+ prog_name: str,1363+ complete_var: t.Optional[str] = None,1364+ ) -> None:1365+ """Check if the shell is asking for tab completion, process1366+ that, then exit early. Called from :meth:`main` before the1367+ program is invoked.1368+1369+ :param prog_name: Name of the executable in the shell.1370+ :param complete_var: Name of the environment variable that holds1371+ the completion instruction. Defaults to1372+ ``_{PROG_NAME}_COMPLETE``.1373+1374+ .. versionchanged:: 8.2.01375+ Dots (``.``) in ``prog_name`` are replaced with underscores (``_``).1376+ """1377+ if complete_var is None:1378+ complete_name = prog_name.replace("-", "_").replace(".", "_")1379+ complete_var = f"_{complete_name}_COMPLETE".upper()1380+1381+ instruction = os.environ.get(complete_var)1382+1383+ if not instruction:1384+ return1385+1386+ from .shell_completion import shell_complete1387+1388+ rv = shell_complete(self, ctx_args, prog_name, complete_var, instruction)1389+ sys.exit(rv)1390+1391+ def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any:1392+ """Alias for :meth:`main`."""1393+ return self.main(*args, **kwargs)1394+1395+1396+class _FakeSubclassCheck(type):1397+ def __subclasscheck__(cls, subclass: type) -> bool:1398+ return issubclass(subclass, cls.__bases__[0])1399+1400+ def __instancecheck__(cls, instance: t.Any) -> bool:1401+ return isinstance(instance, cls.__bases__[0])1402+1403+1404+class _BaseCommand(Command, metaclass=_FakeSubclassCheck):1405+ """1406+ .. deprecated:: 8.21407+ Will be removed in Click 9.0. Use ``Command`` instead.1408+ """1409+1410+1411+1412 class MultiCommand(Command):1413 """A multi command is the basic implementation of a command that1414 dispatches to subcommands. The most common version is the1415 :class:`Group`.1563 unmodified lines2979 return f"'{self.make_metavar()}'"2980 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:2986+ import warnings2987+2988+ if name == "BaseCommand":2989+ warnings.warn(2990+ "'BaseCommand' is deprecated and will be removed in Click 9.0. Use"2991+ " 'Command' instead.",2992+ DeprecationWarning,2993+ stacklevel=2,2994+ )2995+ return _BaseCommand2996+2997+ raise AttributeError(name)modified:src/click/shell_completion.py+5 added-5 removed
2 unmodified lines3 import typing as t4 from gettext import gettext as _5 6 from .core import Argument7-from .core import BaseCommand7+from .core import Command8 from .core import Context9 from .core import MultiCommand10 from .core import Option11 from .core import Parameter2 unmodified lines14 from .utils import echo15 16 17 def shell_complete(18- cli: BaseCommand,18+ cli: Command,19 ctx_args: t.MutableMapping[str, t.Any],20 prog_name: str,21 complete_var: str,22 instruction: str,191 unmodified lines214 """215 216 def __init__(217 self,218- cli: BaseCommand,218+ cli: Command,219 ctx_args: t.MutableMapping[str, t.Any],220 prog_name: str,221 complete_var: str,222 ) -> None:269 unmodified lines492 return last_option is not None and last_option in param.opts493 494 495 def _resolve_context(496- cli: BaseCommand,496+ cli: Command,497 ctx_args: t.MutableMapping[str, t.Any],498 prog_name: str,499 args: t.List[str],500 ) -> Context:49 unmodified lines550 551 552 def _resolve_incomplete(553 ctx: Context, args: t.List[str], incomplete: str554-) -> t.Tuple[t.Union[BaseCommand, Parameter], str]:554+) -> t.Tuple[t.Union[Command, Parameter], str]:555 """Find the Click object that will handle the completion of the556 incomplete value. Return the object and the incomplete value.557 558 :param ctx: Invocation context for the command represented by38 unmodified linesmodified:src/click/testing.py+3 added-3 removed
12 unmodified lines13 from . import utils14 from ._compat import _find_binary_reader15 16 if t.TYPE_CHECKING:17- from .core import BaseCommand17+ from .core import Command18 19 20 class EchoingStdin:21 def __init__(self, input: t.BinaryIO, output: t.BinaryIO) -> None:164 unmodified lines186 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:190+ def get_default_prog_name(self, cli: "Command") -> str:191 """Given a command object it will return the default program name192 for it. The default is the `name` attribute or ``"root"`` if not193 set.194 """152 unmodified lines347 formatting.FORCED_WIDTH = old_forced_width348 349 def invoke(350 self,351- cli: "BaseCommand",351+ cli: "Command",352 args: t.Optional[t.Union[str, t.Sequence[str]]] = None,353 input: t.Optional[t.Union[str, bytes, t.IO[t.Any]]] = None,354 env: t.Optional[t.Mapping[str, t.Optional[str]]] = None,355 catch_exceptions: bool = True,124 unmodified linesmodified:tests/test_commands.py+2 added-2 removed
143 unmodified lines144 assert result.exit_code == exit_code145 assert expect in result.output146 147 148-def test_base_command(runner):148+def test_custom_parser(runner):149 import optparse150 151 @click.group()152 def cli():153 pass154 155- class OptParseCommand(click.BaseCommand):155+ class OptParseCommand(click.Command):156 def __init__(self, name, parser, callback):157 super().__init__(name)158 self.parser = parser159 self.callback = callback252 unmodified linesmodified:CHANGES.rst+2 added
7 unmodified lines8 - Drop support for Python 3.7. :pr:`2588`9 - Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.10 :pr:`326`11 - Use ``flit_core`` instead of ``setuptools`` as build backend.12+- ``BaseCommand`` is deprecated. ``Command`` is the base class for all13+ commands. :issue:`2589`14 15 16 Version 8.1.717 -------------1102 unmodified lines