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
+14 -5
View File
@@ -1,6 +1,9 @@
from rich.console import Console
from argenta.command import Command
from argenta.command.flag.defaults import PredefinedFlags
from argenta.command.flag.models import Flag
from argenta.response import Response
from argenta.router import Router
@@ -9,14 +12,20 @@ work_router: Router = Router(title='Work points:')
console = Console()
@work_router.command(Command('get', 'Get Help', aliases=['help', 'Get_help']))
def command_help():
pass
@work_router.command(Command('get', 'Get Help', aliases=['help', 'Get_help'], flags=PredefinedFlags.PORT))
def command_help(response: Response):
print(response.status)
print(response.undefined_flags.get_flags())
print(response.valid_flags.get_flags())
print(response.invalid_value_flags.get_flags())
@work_router.command(Command('run', 'Run All'))
def command_start_solving():
pass
def command_start_solving(response: Response):
print(response.status)
print(response.undefined_flags.get_flags())
print(response.valid_flags.get_flags())
print(response.invalid_value_flags.get_flags())
+2 -1
View File
@@ -11,7 +11,8 @@ from argenta.orchestrator.argparser.arguments import BooleanArgument
arg_parser = ArgParser(processed_args=[BooleanArgument('repeat')])
app: App = App(dividing_line=DynamicDividingLine(),
autocompleter=AutoCompleter('./mock/.hist'))
autocompleter=AutoCompleter('./mock/.hist'),
repeat_command_groups=False)
orchestrator: Orchestrator = Orchestrator(arg_parser)
+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
+16 -8
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,7 +152,7 @@ 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:],
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)
+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
+31 -13
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)
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
+6 -6
View File
@@ -1,4 +1,4 @@
from argenta.command.flag import Flag, ValidInputFlag, Flags
from argenta.command.flag import Flag, InputFlag, Flags
from argenta.command.models import InputCommand, Command
from argenta.command.exceptions import (UnprocessedInputFlagException,
RepeatedInputFlagsException,
@@ -25,23 +25,23 @@ class TestInputCommand(unittest.TestCase):
def test_validate_correct_input_flag1(self):
command = Command('some', flags=Flag('test'))
self.assertEqual(command.validate_input_flag(ValidInputFlag('test')), True)
self.assertEqual(command.validate_input_flag(InputFlag('test')), True)
def test_validate_correct_input_flag2(self):
command = Command('some', flags=Flags(Flag('test'), Flag('more')))
self.assertEqual(command.validate_input_flag(ValidInputFlag('more')), True)
self.assertEqual(command.validate_input_flag(InputFlag('more')), True)
def test_validate_incorrect_input_flag1(self):
command = Command('some', flags=Flags(Flag('test')))
self.assertEqual(command.validate_input_flag(ValidInputFlag('more')), False)
self.assertEqual(command.validate_input_flag(InputFlag('more')), False)
def test_validate_incorrect_input_flag2(self):
command = Command('some', flags=Flags(Flag('test'), Flag('more')))
self.assertEqual(command.validate_input_flag(ValidInputFlag('case')), False)
self.assertEqual(command.validate_input_flag(InputFlag('case')), False)
def test_validate_incorrect_input_flag3(self):
command = Command('some')
self.assertEqual(command.validate_input_flag(ValidInputFlag('case')), False)
self.assertEqual(command.validate_input_flag(InputFlag('case')), False)
def test_isinstance_parse_correct_raw_command(self):
cmd = InputCommand.parse('ssh --host 192.168.0.3')
+8 -8
View File
@@ -1,4 +1,4 @@
from argenta.command.flag.models import Flag, ValidInputFlag, InputFlags, Flags
from argenta.command.flag.models import Flag, InputFlag, InputFlags, Flags
import unittest
import re
@@ -28,11 +28,11 @@ class TestFlag(unittest.TestCase):
'--')
def test_get_flag_value_without_set(self):
self.assertEqual(ValidInputFlag(name='test').get_value(),
self.assertEqual(InputFlag(name='test').get_value(),
None)
def test_get_flag_value_with_set(self):
flag = ValidInputFlag(name='test')
flag = InputFlag(name='test')
flag.set_value('example')
self.assertEqual(flag.get_value(), 'example')
@@ -69,19 +69,19 @@ class TestFlag(unittest.TestCase):
self.assertEqual(flag.validate_input_flag_value('random value'), True)
def test_get_input_flag1(self):
flag = ValidInputFlag(name='test')
flag = InputFlag(name='test')
input_flags = InputFlags(flag)
self.assertEqual(input_flags.get_flag('test'), flag)
def test_get_input_flag2(self):
flag = ValidInputFlag(name='test')
flag2 = ValidInputFlag(name='some')
flag = InputFlag(name='test')
flag2 = InputFlag(name='some')
input_flags = InputFlags(flag, flag2)
self.assertEqual(input_flags.get_flag('some'), flag2)
def test_get_undefined_input_flag(self):
flag = ValidInputFlag(name='test')
flag2 = ValidInputFlag(name='some')
flag = InputFlag(name='test')
flag2 = InputFlag(name='some')
input_flags = InputFlags(flag, flag2)
self.assertEqual(input_flags.get_flag('case'), None)
+12 -12
View File
@@ -1,4 +1,4 @@
from argenta.command.flag import InputFlags, ValidInputFlag, Flag, Flags
from argenta.command.flag import InputFlags, InputFlag, Flag, Flags
from argenta.router import Router
from argenta.command import Command
from argenta.router.exceptions import (TriggerContainSpacesException,
@@ -27,66 +27,66 @@ class TestRouter(unittest.TestCase):
def test_validate_incorrect_input_flag1(self):
router = Router()
router.set_invalid_input_flag_handler(lambda flag: None)
self.assertEqual(router._validate_input_flags(Command('cmd'), InputFlags(ValidInputFlag('ssh'))), False)
self.assertEqual(router._validate_input_flags(Command('cmd'), InputFlags(InputFlag('ssh'))), False)
def test_validate_incorrect_input_flag2(self):
router = Router()
router.set_invalid_input_flag_handler(lambda flag: None)
self.assertEqual(router._validate_input_flags(Command('cmd'), InputFlags(ValidInputFlag('ssh', value='some'))), False)
self.assertEqual(router._validate_input_flags(Command('cmd'), InputFlags(InputFlag('ssh', value='some'))), False)
def test_validate_incorrect_input_flag3(self):
router = Router()
router.set_invalid_input_flag_handler(lambda flag: None)
command = Command('cmd', flags=Flag('port'))
input_flags = InputFlags(ValidInputFlag('ssh', value='some2'))
input_flags = InputFlags(InputFlag('ssh', value='some2'))
self.assertEqual(router._validate_input_flags(command, input_flags), False)
def test_validate_incorrect_input_flag4(self):
router = Router()
router.set_invalid_input_flag_handler(lambda flag: None)
command = Command('cmd', flags=Flag('ssh', possible_values=False))
input_flags = InputFlags(ValidInputFlag('ssh', value='some3'))
input_flags = InputFlags(InputFlag('ssh', value='some3'))
self.assertEqual(router._validate_input_flags(command, input_flags), False)
def test_validate_incorrect_input_flag5(self):
router = Router()
router.set_invalid_input_flag_handler(lambda flag: None)
command = Command('cmd', flags=Flag('ssh', possible_values=re.compile(r'some[1-5]$')))
input_flags = InputFlags(ValidInputFlag('ssh', value='some40'))
input_flags = InputFlags(InputFlag('ssh', value='some40'))
self.assertEqual(router._validate_input_flags(command, input_flags), False)
def test_validate_incorrect_input_flag6(self):
router = Router()
router.set_invalid_input_flag_handler(lambda flag: None)
command = Command('cmd', flags=Flag('ssh', possible_values=['example']))
input_flags = InputFlags(ValidInputFlag('ssh', value='example2'))
input_flags = InputFlags(InputFlag('ssh', value='example2'))
self.assertEqual(router._validate_input_flags(command, input_flags), False)
def test_validate_incorrect_input_flag7(self):
router = Router()
router.set_invalid_input_flag_handler(lambda flag: None)
command = Command('cmd', flags=Flag('ssh', possible_values=['example']))
input_flags = InputFlags(ValidInputFlag('ssh'))
input_flags = InputFlags(InputFlag('ssh'))
self.assertEqual(router._validate_input_flags(command, input_flags), False)
def test_validate_correct_input_flag1(self):
command = Command('cmd', flags=Flag('port'))
input_flags = InputFlags(ValidInputFlag('port', value='some2'))
input_flags = InputFlags(InputFlag('port', value='some2'))
self.assertEqual(Router()._validate_input_flags(command, input_flags), True)
def test_validate_correct_input_flag2(self):
command = Command('cmd', flags=Flag('port', possible_values=['some2', 'some3']))
input_flags = InputFlags(ValidInputFlag('port', value='some2'))
input_flags = InputFlags(InputFlag('port', value='some2'))
self.assertEqual(Router()._validate_input_flags(command, input_flags), True)
def test_validate_correct_input_flag3(self):
command = Command('cmd', flags=Flag('ssh', possible_values=re.compile(r'more[1-5]$')))
input_flags = InputFlags(ValidInputFlag('ssh', value='more5'))
input_flags = InputFlags(InputFlag('ssh', value='more5'))
self.assertEqual(Router()._validate_input_flags(command, input_flags), True)
def test_validate_correct_input_flag4(self):
command = Command('cmd', flags=Flag('ssh', possible_values=False))
input_flags = InputFlags(ValidInputFlag('ssh'))
input_flags = InputFlags(InputFlag('ssh'))
self.assertEqual(Router()._validate_input_flags(command, input_flags), True)
def test_validate_incorrect_func_args1(self):