work on Response model

This commit is contained in:
2025-04-29 00:07:32 +03:00
parent eb43806da6
commit 9d6598c4e0
15 changed files with 133 additions and 101 deletions
+4 -6
View File
@@ -16,6 +16,7 @@ from argenta.command.exceptions import (UnprocessedInputFlagException,
EmptyInputCommandException,
BaseInputCommandException)
from argenta.app.registered_routers.entity import RegisteredRouters
from argenta.response import Response
@@ -58,7 +59,7 @@ class BaseApp:
self._repeated_input_flags_handler: Callable[[str], None] = lambda raw_command: print_func(f'Repeated input flags: {raw_command}')
self._empty_input_command_handler: Callable[[], None] = lambda: print_func('Empty input command')
self._unknown_command_handler: Callable[[InputCommand], None] = lambda command: print_func(f"Unknown command: {command.get_trigger()}")
self._exit_command_handler: Callable[[], None] = lambda: print_func(self._farewell_message)
self._exit_command_handler: Callable[[Response], None] = lambda response: print_func(self._farewell_message)
def set_description_message_pattern(self, _: Callable[[str, str], str]) -> None:
@@ -210,8 +211,8 @@ class BaseApp:
system_router.set_title(self._system_router_title)
@system_router.command(self._exit_command)
def exit_command():
self._exit_command_handler()
def exit_command(response: Response) -> None:
self._exit_command_handler(response)
if system_router not in self._registered_routers.get_registered_routers():
system_router.set_command_register_ignore(self._ignore_command_register)
@@ -346,9 +347,6 @@ class App(BaseApp):
res: str = f.getvalue()
self._print_framed_text(res)
if not self._repeat_command_groups_description:
self._print_func(self._prompt)
def include_router(self, router: Router) -> None:
"""
+2 -2
View File
@@ -1,4 +1,4 @@
from argenta.command.flag.models import ValidInputFlag, Flag
from argenta.command.flag.models import Flag, InputFlag
class BaseInputCommandException(Exception):
@@ -20,7 +20,7 @@ class RepeatedInputFlagsException(BaseInputCommandException):
"""
Private. Raised when repeated input flags are detected
"""
def __init__(self, flag: Flag | ValidInputFlag):
def __init__(self, flag: Flag | InputFlag):
self.flag = flag
def __str__(self):
return ("Repeated Input Flags\n"
-3
View File
@@ -1,4 +1 @@
__all__ = ('InputFlags', 'ValidInputFlag', 'Flag', 'Flags')
from argenta.command.flag.models import InputFlags, ValidInputFlag, Flags, Flag
+3 -13
View File
@@ -1,8 +1,8 @@
from typing import Literal, Pattern
from abc import ABC, abstractmethod
class BaseFlag(ABC):
class BaseFlag:
def __init__(self, name: str,
prefix: Literal['-', '--', '---'] = '--') -> None:
"""
@@ -37,7 +37,6 @@ class BaseFlag(ABC):
return self._prefix
class Flag(BaseFlag):
def __init__(self, name: str,
prefix: Literal['-', '--', '---'] = '--',
@@ -82,8 +81,7 @@ class Flag(BaseFlag):
return True
class ValidInputFlag(BaseFlag):
class InputFlag(BaseFlag):
def __init__(self, name: str,
prefix: Literal['-', '--', '---'] = '--',
value: str = None):
@@ -112,11 +110,3 @@ class ValidInputFlag(BaseFlag):
"""
self._flag_value = value
class UndefinedInputFlag(ValidInputFlag): pass
class InvalidValueInputFlag(ValidInputFlag): pass
+21 -15
View File
@@ -1,9 +1,13 @@
from argenta.command.flag import Flag, ValidInputFlag
from argenta.command.flag.models import InputFlag, Flag
from typing import Generic, TypeVar
class Flags:
def __init__(self, *flags: Flag):
FlagType = TypeVar('FlagType')
class BaseFlags(Generic[FlagType]):
def __init__(self, *flags: FlagType):
"""
Public. A model that combines the registered flags
:param flags: the flags that will be registered
@@ -11,14 +15,14 @@ class Flags:
"""
self._flags = flags if flags else []
def get_flags(self) -> list[Flag]:
def get_flags(self) -> list[FlagType]:
"""
Public. Returns a list of flags
:return: list of flags
:return: list of flags as list[FlagType]
"""
return self._flags
def add_flag(self, flag: Flag):
def add_flag(self, flag: FlagType):
"""
Public. Adds a flag to the list of flags
:param flag: flag to add
@@ -26,7 +30,7 @@ class Flags:
"""
self._flags.append(flag)
def add_flags(self, flags: list[Flag]):
def add_flags(self, flags: list[FlagType]):
"""
Public. Adds a list of flags to the list of flags
:param flags: list of flags to add
@@ -34,7 +38,7 @@ class Flags:
"""
self._flags.extend(flags)
def get_flag(self, name: str) -> Flag | None:
def get_flag(self, name: str) -> FlagType | None:
"""
Public. Returns the flag entity by its name or None if not found
:param name: the name of the flag to get
@@ -55,15 +59,17 @@ class Flags:
return self._flags[item]
class ValidInputFlags(ValidInputFlag):
pass
class Flags(BaseFlags[Flag]): pass
class UndefinedInputFlags(ValidInputFlags):
pass
class InputFlags(BaseFlags[InputFlag]): pass
class InvalidValueInputFlags(ValidInputFlags):
pass
class ValidInputFlags(InputFlags): pass
class UndefinedInputFlags(InputFlags): pass
class InvalidValueInputFlags(InputFlags): pass
+19 -11
View File
@@ -1,4 +1,5 @@
from argenta.command.flag.models import Flag, ValidInputFlag, Flags, InputFlags
from argenta.command.flag.models import Flag, InputFlag
from argenta.command.flags.models import InputFlags, Flags
from argenta.command.exceptions import (UnprocessedInputFlagException,
RepeatedInputFlagsException,
EmptyInputCommandException)
@@ -55,7 +56,7 @@ class Command(BaseCommand):
"""
return self._aliases
def validate_input_flag(self, flag: ValidInputFlag) -> bool:
def validate_input_flag(self, flag: InputFlag) -> Literal['Undefined', 'Valid', 'Invalid']:
"""
Private. Validates the input flag
:param flag: input flag for validation
@@ -67,14 +68,21 @@ class Command(BaseCommand):
if registered_flags.get_string_entity() == flag.get_string_entity():
is_valid = registered_flags.validate_input_flag_value(flag.get_value())
if is_valid:
return True
return 'Valid'
else:
return 'Invalid'
else:
return 'Undefined'
else:
for registered_flag in registered_flags:
if registered_flag.get_string_entity() == flag.get_string_entity():
is_valid = registered_flag.validate_input_flag_value(flag.get_value())
if is_valid:
return True
return False
return 'Valid'
else:
return 'Invalid'
return 'Undefined'
return 'Undefined'
def get_description(self) -> str:
"""
@@ -87,7 +95,7 @@ class Command(BaseCommand):
class InputCommand(BaseCommand, Generic[InputCommandType]):
def __init__(self, trigger: str,
input_flags: ValidInputFlag | InputFlags = None):
input_flags: InputFlag | InputFlags = None):
"""
Private. The model of the input command, after parsing
:param trigger:the trigger of the command
@@ -95,7 +103,7 @@ class InputCommand(BaseCommand, Generic[InputCommandType]):
:return: None
"""
super().__init__(trigger)
self._input_flags: InputFlags = input_flags if isinstance(input_flags, InputFlags) else InputFlags(input_flags) if isinstance(input_flags, ValidInputFlag) else InputFlags()
self._input_flags: InputFlags = input_flags if isinstance(input_flags, InputFlags) else InputFlags(input_flags) if isinstance(input_flags, InputFlag) else InputFlags()
def _set_input_flags(self, input_flags: InputFlags) -> None:
"""
@@ -144,10 +152,10 @@ class InputCommand(BaseCommand, Generic[InputCommandType]):
if not list_of_tokens[k+1].startswith('-'):
continue
input_flag = ValidInputFlag(name=current_flag_name[current_flag_name.rfind('-') + 1:],
prefix=cast(Literal['-', '--', '---'],
current_flag_name[:current_flag_name.rfind('-')+1]),
value=current_flag_value)
input_flag = InputFlag(name=current_flag_name[current_flag_name.rfind('-') + 1:],
prefix=cast(Literal['-', '--', '---'],
current_flag_name[:current_flag_name.rfind('-')+1]),
value=current_flag_value)
all_flags = [flag.get_string_entity() for flag in input_flags.get_flags()]
if input_flag.get_string_entity() not in all_flags:
+5
View File
@@ -0,0 +1,5 @@
from argenta.response.entity import Response
from argenta.response.status import Status
__all__ = ['Response', 'Status']
+4 -4
View File
@@ -3,10 +3,10 @@ from argenta.response.status import Status
class Response:
def __init__(self, status: Status,
valid_flags: ValidInputFlags = None,
undefined_flags: UndefinedInputFlags = None,
invalid_value_flags: InvalidValueInputFlags = None):
def __init__(self, status: Status = None,
valid_flags: ValidInputFlags = ValidInputFlags(),
undefined_flags: UndefinedInputFlags = UndefinedInputFlags(),
invalid_value_flags: InvalidValueInputFlags = InvalidValueInputFlags()):
self.status = status
self.valid_flags = valid_flags
self.undefined_flags = undefined_flags
+1 -1
View File
@@ -1,7 +1,7 @@
from typing import Callable, Iterator
from argenta.command import Command
from argenta.command.flag import InputFlags
from argenta.command.flags.models import InputFlags
+32 -14
View File
@@ -1,10 +1,11 @@
from typing import Callable
from typing import Callable, Literal
from inspect import getfullargspec
from argenta.command import Command
from argenta.command.models import InputCommand
from argenta.response import Response, Status
from argenta.router.command_handler.entity import CommandHandlers, CommandHandler
from argenta.command.flag.models import Flag
from argenta.command.flags.models import Flags
from argenta.command.flags.models import Flags, InputFlags, UndefinedInputFlags, ValidInputFlags, InvalidValueInputFlags
from argenta.router.exceptions import (RepeatedFlagNameException,
TooManyTransferredArgsException,
RequiredArgumentNotPassedException,
@@ -69,36 +70,53 @@ class Router:
:return: None
"""
handle_command = command_handler.get_handled_command()
response: Response = Response()
if handle_command.get_registered_flags().get_flags():
if input_command_flags.get_flags():
if self._validate_input_flags(handle_command, input_command_flags):
command_handler.handling(input_command_flags)
return
response.status = Status.SUCCESSFUL
flags = self._validate_input_flags(handle_command, input_command_flags)
response.valid_flags, response.undefined_flags, response.invalid_flags = flags
command_handler.handling(response)
return
else:
command_handler.handling(input_command_flags)
response.status = Status.SUCCESSFUL
command_handler.handling(response)
return
else:
if input_command_flags.get_flags():
self._not_valid_flag_handler(input_command_flags[0])
response.status = Status.UNSUCCESSFUL
response.undefined_flags = UndefinedInputFlags(*input_command_flags)
command_handler.handling(response)
return
else:
command_handler.handling()
response.status = Status.SUCCESSFUL
command_handler.handling(response)
return
def _validate_input_flags(self, handled_command: Command, input_flags: InputFlags) -> bool:
@staticmethod
def _validate_input_flags(handled_command: Command, input_flags: InputFlags) -> (ValidInputFlags,
UndefinedInputFlags,
InvalidValueInputFlags):
"""
Private. Validates flags of input command
:param handled_command: entity of the handled command
:param input_flags:
:return: is flags of input command valid as bool
"""
valid_input_flags: ValidInputFlags = ValidInputFlags()
invalid_value_input_flags: InvalidValueInputFlags = InvalidValueInputFlags()
undefined_input_flags: UndefinedInputFlags = UndefinedInputFlags()
for flag in input_flags:
is_valid: bool = handled_command.validate_input_flag(flag)
if not is_valid:
self._not_valid_flag_handler(flag)
return False
return True
flag_status: Literal['Undefined', 'Valid', 'Invalid'] = handled_command.validate_input_flag(flag)
match flag_status:
case 'Valid':
valid_input_flags.add_flag(flag)
case 'Undefined':
undefined_input_flags.add_flag(flag)
case 'Invalid':
invalid_value_input_flags.add_flag(flag)
return valid_input_flags, undefined_input_flags, invalid_value_input_flags
@staticmethod