This commit is contained in:
2025-02-08 00:57:21 +03:00
parent 3f88c5278e
commit c78609caca
4 changed files with 67 additions and 44 deletions
+35 -35
View File
@@ -13,56 +13,56 @@ class App:
prompt: str = 'Enter a command', prompt: str = 'Enter a command',
exit_command: str = 'q', exit_command: str = 'q',
ignore_exit_command_register: bool = True, ignore_exit_command_register: bool = True,
initial_greeting: str = 'Hello', initial_greeting: str = '\nHello, I am Argenta\n',
goodbye_message: str = 'GoodBye', farewell_message: str = 'GoodBye',
line_separate: str = '\n', line_separate: str = '',
command_group_description_separate: str = '\n', command_group_description_separate: str = '',
print_func: Callable[[str], None] = print) -> None: print_func: Callable[[str], None] = print) -> None:
self.prompt = prompt self.prompt = prompt
self.print_func = print_func self.print_func = print_func
self.exit_command = exit_command self.exit_command = exit_command
self.ignore_exit_command_register = ignore_exit_command_register self.ignore_exit_command_register = ignore_exit_command_register
self.goodbye_message = goodbye_message self.farewell_message = farewell_message
self.initial_greeting = initial_greeting self.initial_greeting = initial_greeting
self.line_separate = line_separate self.line_separate = line_separate
self.command_group_description_separate = command_group_description_separate self.command_group_description_separate = command_group_description_separate
self.routers: list[Router] = [] self._routers: list[Router] = []
self.registered_commands: list[dict[str, str | list[dict[str, Callable[[], None] | str]] | Router]] = [] self._registered_commands: list[dict[str, str | list[dict[str, Callable[[], None] | str]] | Router]] = []
self.main_app_router: Router | None = None self._main_app_router: Router | None = None
self._description_message_pattern = '[{command}] *=*=* {description}' self._description_message_pattern: str = '[{command}] *=*=* {description}'
def start_polling(self) -> None: def start_polling(self) -> None:
self.print_func(self.initial_greeting) self.print_func(self.initial_greeting)
self.validate_main_router() self._validate_main_router()
while True: while True:
self.print_command_group_description() self._print_command_group_description()
self.print_func(self.prompt) self.print_func(self.prompt)
command: str = input() command: str = input()
self.checking_command_for_exit_command(command) self._checking_command_for_exit_command(command)
self.print_func(self.line_separate) self.print_func(self.line_separate)
is_unknown_command: bool = self.check_is_command_unknown(command) is_unknown_command: bool = self._check_is_command_unknown(command)
if is_unknown_command: if is_unknown_command:
continue continue
for router in self.routers: for router in self._routers:
router.input_command_handler(command) router.input_command_handler(command)
self.print_func(self.line_separate) self.print_func(self.line_separate)
self.print_func(self.command_group_description_separate) self.print_func(self.command_group_description_separate)
def set_initial_greeting(self, greeting: str) -> None: def set_initial_greeting(self, greeting: str) -> None:
self.initial_greeting = greeting self.initial_greeting: str = greeting
def set_goodbye_message(self, message: str) -> None: def set_farewell_message(self, message: str) -> None:
self.goodbye_message = message self.farewell_message: str = message
def set_description_message_pattern(self, pattern: str) -> None: def set_description_message_pattern(self, pattern: str) -> None:
@@ -71,34 +71,34 @@ class App:
description='description') description='description')
except KeyError: except KeyError:
raise InvalidDescriptionMessagePatternException(pattern) raise InvalidDescriptionMessagePatternException(pattern)
self._description_message_pattern = pattern self._description_message_pattern: str = pattern
def validate_main_router(self): def _validate_main_router(self):
if not self.main_app_router: if not self._main_app_router:
raise MissingMainRouterException() raise MissingMainRouterException()
if not self.main_app_router.unknown_command_func: if not self._main_app_router.unknown_command_func:
raise MissingHandlersForUnknownCommandsOnMainRouterException() raise MissingHandlersForUnknownCommandsOnMainRouterException()
for router in self.routers: for router in self._routers:
if router.unknown_command_func and self.main_app_router is not router: if router.unknown_command_func and self._main_app_router is not router:
raise HandlerForUnknownCommandsCanOnlyBeDeclaredForMainRouterException() raise HandlerForUnknownCommandsCanOnlyBeDeclaredForMainRouterException()
def checking_command_for_exit_command(self, command: str): def _checking_command_for_exit_command(self, command: str):
if command.lower() == self.exit_command.lower(): if command.lower() == self.exit_command.lower():
if self.ignore_exit_command_register: if self.ignore_exit_command_register:
self.print_func(self.goodbye_message) self.print_func(self.farewell_message)
exit(0) exit(0)
else: else:
if command == self.exit_command: if command == self.exit_command:
self.print_func(self.goodbye_message) self.print_func(self.farewell_message)
exit(0) exit(0)
def check_is_command_unknown(self, command: str): def _check_is_command_unknown(self, command: str):
registered_commands = self.registered_commands registered_commands: list[dict[str, str | list[dict[str, Callable[[], None] | str]] | Router]] = self._registered_commands
for router in registered_commands: for router in registered_commands:
for command_entity in router['commands']: for command_entity in router['commands']:
if command_entity['command'].lower() == command.lower(): if command_entity['command'].lower() == command.lower():
@@ -107,14 +107,14 @@ class App:
else: else:
if command_entity['command'] == command: if command_entity['command'] == command:
return False return False
self.main_app_router.unknown_command_handler(command) self._main_app_router.unknown_command_handler(command)
self.print_func(self.line_separate) self.print_func(self.line_separate)
self.print_func(self.command_group_description_separate) self.print_func(self.command_group_description_separate)
return True return True
def print_command_group_description(self): def _print_command_group_description(self):
for router in self.registered_commands: for router in self._registered_commands:
self.print_func(router['name']) self.print_func(router['name'])
for command_entity in router['commands']: for command_entity in router['commands']:
self.print_func(self._description_message_pattern.format( self.print_func(self._description_message_pattern.format(
@@ -130,16 +130,16 @@ class App:
raise InvalidRouterInstanceException() raise InvalidRouterInstanceException()
if is_main: if is_main:
if not self.main_app_router: if not self._main_app_router:
self.main_app_router = router self._main_app_router = router
router.set_router_as_main() router.set_router_as_main()
else: else:
raise OnlyOneMainRouterIsAllowedException(router) raise OnlyOneMainRouterIsAllowedException(router)
self.routers.append(router) self._routers.append(router)
registered_commands: list[dict[str, Callable[[], None] | str]] = router.get_registered_commands() registered_commands: list[dict[str, Callable[[], None] | str]] = router.get_registered_commands()
self.registered_commands.append({'name': router.get_name(), self._registered_commands.append({'name': router.get_name(),
'router': router, 'router': router,
'commands': registered_commands}) 'commands': registered_commands})
+9 -8
View File
@@ -9,10 +9,10 @@ class Router:
name: str, name: str,
ignore_command_register: bool = False): ignore_command_register: bool = False):
self.ignore_command_register: bool = ignore_command_register self.ignore_command_register = ignore_command_register
self._name = name self.name = name
self.processed_commands: list[dict[str, Callable[[], None] | str]] = [] self._processed_commands: list[dict[str, Callable[[], None] | str]] = []
self.unknown_command_func: Callable[[str], None] | None = None self.unknown_command_func: Callable[[str], None] | None = None
self._is_main_router: bool = False self._is_main_router: bool = False
@@ -24,7 +24,7 @@ class Router:
raise InvalidDescriptionInstanceException() raise InvalidDescriptionInstanceException()
else: else:
def command_decorator(func): def command_decorator(func):
self.processed_commands.append({'func': func, self._processed_commands.append({'func': func,
'command': command, 'command': command,
'description': description}) 'description': description})
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
@@ -37,7 +37,7 @@ class Router:
if self.unknown_command_func is not None: if self.unknown_command_func is not None:
raise UnknownCommandHandlerHasAlreadyBeenCreatedException() raise UnknownCommandHandlerHasAlreadyBeenCreatedException()
self.unknown_command_func = func self.unknown_command_func: Callable = func
def wrapper(*args, **kwargs): def wrapper(*args, **kwargs):
return func(*args, **kwargs) return func(*args, **kwargs)
@@ -45,7 +45,7 @@ class Router:
def input_command_handler(self, input_command): def input_command_handler(self, input_command):
for command_entity in self.processed_commands: for command_entity in self._processed_commands:
if input_command.lower() == command_entity['command'].lower(): if input_command.lower() == command_entity['command'].lower():
if self.ignore_command_register: if self.ignore_command_register:
return command_entity['func']() return command_entity['func']()
@@ -53,6 +53,7 @@ class Router:
if input_command == command_entity['command']: if input_command == command_entity['command']:
return command_entity['func']() return command_entity['func']()
def unknown_command_handler(self, unknown_command): def unknown_command_handler(self, unknown_command):
self.unknown_command_func(unknown_command) self.unknown_command_func(unknown_command)
@@ -62,9 +63,9 @@ class Router:
def get_registered_commands(self) -> list[dict[str, Callable[[], None] | str]]: def get_registered_commands(self) -> list[dict[str, Callable[[], None] | str]]:
return self.processed_commands return self._processed_commands
def get_name(self) -> str: def get_name(self) -> str:
return self._name return self.name
Generated
+22 -1
View File
@@ -364,6 +364,27 @@ pygments = ">=2.13.0,<3.0.0"
[package.extras] [package.extras]
jupyter = ["ipywidgets (>=7.5.1,<9)"] jupyter = ["ipywidgets (>=7.5.1,<9)"]
[[package]]
name = "setuptools"
version = "75.8.0"
description = "Easily download, build, install, upgrade, and uninstall Python packages"
optional = false
python-versions = ">=3.9"
groups = ["dev"]
files = [
{file = "setuptools-75.8.0-py3-none-any.whl", hash = "sha256:e3982f444617239225d675215d51f6ba05f845d4eec313da4418fdbb56fb27e3"},
{file = "setuptools-75.8.0.tar.gz", hash = "sha256:c5afc8f407c626b8313a86e10311dd3f661c6cd9c09d4bf8c15c0e11f9f2b0e6"},
]
[package.extras]
check = ["pytest-checkdocs (>=2.4)", "pytest-ruff (>=0.2.1)", "ruff (>=0.8.0)"]
core = ["importlib_metadata (>=6)", "jaraco.collections", "jaraco.functools (>=4)", "jaraco.text (>=3.7)", "more_itertools", "more_itertools (>=8.8)", "packaging", "packaging (>=24.2)", "platformdirs (>=4.2.2)", "tomli (>=2.0.1)", "wheel (>=0.43.0)"]
cover = ["pytest-cov"]
doc = ["furo", "jaraco.packaging (>=9.3)", "jaraco.tidelift (>=1.4)", "pygments-github-lexers (==0.0.5)", "pyproject-hooks (!=1.1)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-favicon", "sphinx-inline-tabs", "sphinx-lint", "sphinx-notfound-page (>=1,<2)", "sphinx-reredirects", "sphinxcontrib-towncrier", "towncrier (<24.7)"]
enabler = ["pytest-enabler (>=2.2)"]
test = ["build[virtualenv] (>=1.0.3)", "filelock (>=3.4.0)", "ini2toml[lite] (>=0.14)", "jaraco.develop (>=7.21)", "jaraco.envs (>=2.2)", "jaraco.path (>=3.7.2)", "jaraco.test (>=5.5)", "packaging (>=24.2)", "pip (>=19.1)", "pyproject-hooks (!=1.1)", "pytest (>=6,!=8.1.*)", "pytest-home (>=0.5)", "pytest-perf", "pytest-subprocess", "pytest-timeout", "pytest-xdist (>=3)", "tomli-w (>=1.0.0)", "virtualenv (>=13.0.0)", "wheel (>=0.44.0)"]
type = ["importlib_metadata (>=7.0.2)", "jaraco.develop (>=7.21)", "mypy (==1.14.*)", "pytest-mypy"]
[[package]] [[package]]
name = "tqdm" name = "tqdm"
version = "4.67.1" version = "4.67.1"
@@ -418,4 +439,4 @@ files = [
[metadata] [metadata]
lock-version = "2.1" lock-version = "2.1"
python-versions = ">=3.11" python-versions = ">=3.11"
content-hash = "61ebe0a43acaa93a239e62954a5cbf5819db0144f4bdc58d86b78b925b0146e6" content-hash = "6d71ae12bf4fc44dab312c9626aff93bbc4f5928bf439f144c07de5d9c93d43f"
+1
View File
@@ -24,4 +24,5 @@ word2number = "^1.1"
numexpr = "^2.10.2" numexpr = "^2.10.2"
requests = "^2.32.3" requests = "^2.32.3"
tqdm = "^4.67.1" tqdm = "^4.67.1"
setuptools = "^75.8.0"