def set_default(self, default: Optional[Any] = None) -> None: if self._required and default is not None: raise LogicException("Cannot set a default value for required arguments") if self._is_list: if default is None: default = [] elif not isinstance(default, list): raise LogicException( "A default value for a list argument must be a list" ) self._default = default
def set_default(self, default: Optional[Any] = None) -> None: if self._flag and default is not None: raise LogicException("A flag option cannot have a default value") if self._is_list: if default is None: default = [] elif not isinstance(default, list): raise LogicException( "A default value for a list option must be a list") if self._flag: default = False self._default = default
def register_factory(self, command_name: str, factory: Callable[[], Command]) -> None: if command_name in self._factories: raise LogicException( f'The command "{command_name}" already exists.') self._factories[command_name] = factory
def add_option(self, option: Option) -> None: if option.name in self._options and option != self._options[ option.name]: raise LogicException( f'An option named "{option.name}" already exists') if option.shortcut: for shortcut in option.shortcut.split("|"): if shortcut in self._shortcuts and option != self._shortcuts[ shortcut]: raise LogicException( f'An option with shortcut "{shortcut}" already exists') self._options[option.name] = option if option.shortcut: for shortcut in option.shortcut.split("|"): self._shortcuts[shortcut] = option.name
def add_argument(self, argument: Argument) -> None: if argument.name in self._arguments: raise LogicException( f'An argument with name "{argument.name}" already exists') if self._has_a_list_argument: raise LogicException( "Cannot add an argument after a list argument") if argument.is_required() and self._has_optional: raise LogicException( "Cannot add a required argument after an optional one") if argument.is_list(): self._has_a_list_argument = True if argument.is_required(): self._required_count += 1 else: self._has_optional = True self._arguments[argument.name] = argument
def __init__( self, name: str, shortcut: Optional[str] = None, flag: bool = True, requires_value: bool = True, is_list: bool = False, description: Optional[str] = None, default: Optional[Any] = None, ) -> None: if name.startswith("--"): name = name[2:] if not name: raise ValueException("An option name cannot be empty") if shortcut is not None: shortcuts = re.split(r"\|-?", shortcut.lstrip("-")) shortcuts = [s for s in shortcuts if s] shortcut = "|".join(shortcuts) if not shortcut: raise ValueException("An option shortcut cannot be empty") self._name = name self._shortcut = shortcut self._flag = flag self._requires_value = requires_value self._is_list = is_list self._description = description or "" self._default = None if self._is_list and self._flag: raise LogicException("A flag option cannot be a list as well") self.set_default(default)