Install a new command function into the CLI. :param command_func_name: name of command function to add This points to the command method and may differ from the method's name if it's being used as a synonym. (e.g. do_exit =
(self, command_func_name: str, command_method: BoundCommandFunc, context: str = "")
| 947 | return parser |
| 948 | |
| 949 | def _install_command_function(self, command_func_name: str, command_method: BoundCommandFunc, context: str = "") -> None: |
| 950 | """Install a new command function into the CLI. |
| 951 | |
| 952 | :param command_func_name: name of command function to add |
| 953 | This points to the command method and may differ from the method's |
| 954 | name if it's being used as a synonym. (e.g. do_exit = do_quit) |
| 955 | :param command_method: the actual command method which runs when the command function is called |
| 956 | :param context: optional info to provide in error message. (e.g. class this function belongs to) |
| 957 | :raises CommandSetRegistrationError: if the command function fails to install |
| 958 | """ |
| 959 | # command_func_name must begin with COMMAND_FUNC_PREFIX to be identified as a command by cmd2. |
| 960 | if not command_func_name.startswith(COMMAND_FUNC_PREFIX): |
| 961 | raise CommandSetRegistrationError(f"{command_func_name} does not begin with '{COMMAND_FUNC_PREFIX}'") |
| 962 | |
| 963 | # command_method must start with COMMAND_FUNC_PREFIX for use in self.command_parsers. |
| 964 | if not command_method.__name__.startswith(COMMAND_FUNC_PREFIX): |
| 965 | raise CommandSetRegistrationError(f"{command_method.__name__} does not begin with '{COMMAND_FUNC_PREFIX}'") |
| 966 | |
| 967 | command = command_func_name[len(COMMAND_FUNC_PREFIX) :] |
| 968 | |
| 969 | # Make sure command function doesn't share name with existing attribute |
| 970 | if hasattr(self, command_func_name): |
| 971 | raise CommandSetRegistrationError(f"Attribute already exists: {command_func_name} ({context})") |
| 972 | |
| 973 | # Check if command has an invalid name |
| 974 | valid, errmsg = self.statement_parser.is_valid_command(command) |
| 975 | if not valid: |
| 976 | raise CommandSetRegistrationError(f"Invalid command name '{command}': {errmsg}") |
| 977 | |
| 978 | # Check if command shares a name with an alias |
| 979 | if command in self.aliases: |
| 980 | self.pwarning(f"Deleting alias '{command}' because it shares its name with a new command") |
| 981 | del self.aliases[command] |
| 982 | |
| 983 | # Check if command shares a name with a macro |
| 984 | if command in self.macros: |
| 985 | self.pwarning(f"Deleting macro '{command}' because it shares its name with a new command") |
| 986 | del self.macros[command] |
| 987 | |
| 988 | setattr(self, command_func_name, command_method) |
| 989 | |
| 990 | def _install_completer_function(self, cmd_name: str, cmd_completer: BoundCompleter) -> None: |
| 991 | completer_func_name = COMPLETER_FUNC_PREFIX + cmd_name |