add metrics concept

This commit is contained in:
2025-05-12 16:22:29 +03:00
parent c38fe10006
commit 8b06e9cd39
19 changed files with 57 additions and 123 deletions
View File
-27
View File
@@ -1,27 +0,0 @@
from mock.mock_app.handlers.routers import work_router
from argenta.app import App
from argenta.app.defaults import PredefinedMessages
from argenta.app.autocompleter import AutoCompleter
from argenta.orchestrator import Orchestrator
from argenta.orchestrator.argparser import ArgParser
from argenta.orchestrator.argparser.arguments import BooleanArgument
arg_parser = ArgParser(processed_args=[BooleanArgument("repeat")])
app: App = App(autocompleter=AutoCompleter(".hist"))
orchestrator: Orchestrator = Orchestrator()
def main():
app.include_router(work_router)
app.add_message_on_startup(PredefinedMessages.USAGE)
app.add_message_on_startup(PredefinedMessages.AUTOCOMPLETE)
app.add_message_on_startup(PredefinedMessages.HELP)
orchestrator.start_polling(app)
if __name__ == "__main__":
main()
+12 -69
View File
@@ -1,85 +1,28 @@
from argenta.router import Router
from argenta.command import Command
from argenta.response import Response
from argenta.metrics import get_time_of_pre_cycle_setup
from argenta.response.status import Status
from argenta.command.flag import Flag
from argenta.command.flags import Flags
from argenta.command.flag import Flag, Flags
from argenta.app import App
from argenta.orchestrator import Orchestrator
# Создание маршрутизатора
file_router = Router("Операции с файлами")
# Определение флагов для команды копирования
copy_flags = Flags(
Flag('source', '--'),
Flag('destination', '--'),
Flag('recursive', '--', False), # Булевый флаг без значения
Flag('force', '-', False) # Короткий булевый флаг
)
@file_router.command(Command('case', aliases=['cp', 'ch']))
router = Router()
for i in range(10000):
trigger = f"cmd{i}"
@router.command(Command(trigger, aliases=[f'dfs{i}', f'fds{i}']))
def handler(response: Response):
print('test')
# Регистрация команды копирования
@file_router.command(Command(
trigger="ch",
description="Копирование файлов",
flags=copy_flags,
aliases=["cp"]
))
def copy_files(response: Response):
# Получаем значения корректных флагов
source = None
destination = None
recursive = False
force = False
for flag in response.valid_flags:
if flag.get_name() == "source":
source = flag.get_value()
elif flag.get_name() == "destination":
destination = flag.get_value()
elif flag.get_name() == "recursive":
recursive = True
elif flag.get_name() == "force":
force = True
# Проверка обязательных параметров
if not source or not destination:
print("Ошибка: необходимо указать источник и назначение")
return
print(f"Копирование из {source} в {destination}")
if recursive:
print("Рекурсивное копирование включено")
if force:
print("Принудительное копирование включено")
# Обработка неопределенных флагов
if response.undefined_flags:
print("\nПредупреждение: обнаружены незарегистрированные флаги:")
for flag in response.undefined_flags:
print(f" - {flag.get_name()}" +
(f" = {flag.get_value()}" if flag.get_value() else ""))
# Обработка флагов с некорректными значениями
if response.invalid_value_flags:
print("\nПредупреждение: обнаружены флаги с некорректными значениями:")
for flag in response.invalid_value_flags:
print(f" - {flag.get_name()} = {flag.get_value()}")
# Принятие решения на основе статуса
if response.status != Status.ALL_FLAGS_VALID:
print("\nВыполнение с предупреждениями из-за проблем с флагами.")
print(response.status)
app = App()
app.include_router(file_router)
orchestrator = Orchestrator()
app = App(repeat_command_groups=False)
app.include_router(router)
orchestrator.start_polling(app)
print(get_time_of_pre_cycle_setup(app))
View File
@@ -1,12 +0,0 @@
from rich.console import Console
console = Console()
def help_command():
console.print(
"[italic bold]The main functionality of the script is to convert an expression from a string "
"to a mathematical one and then calculate this expression. "
"Project GitHub: https://github.com/koloideal/WordMath[/italic bold]"
)
+1 -1
View File
@@ -1,4 +1,4 @@
from mock.mock_app.handlers.routers import work_router
from mock.mock_app.routers import work_router
from argenta.app import App
from argenta.app.defaults import PredefinedMessages
@@ -2,7 +2,7 @@ from rich.console import Console
from argenta.command import Command
from argenta.command.flag.defaults import PredefinedFlags
from argenta.command.flags import Flags
from argenta.command.flag import Flags
from argenta.response import Response
from argenta.router import Router
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "argenta"
version = "1.0.4"
version = "1.0.5"
description = "Python library for building modular CLI applications"
authors = [{ name = "kolo", email = "kolo.is.main@gmail.com" }]
requires-python = ">=3.8"
+2 -2
View File
@@ -1,7 +1,7 @@
from enum import Enum
from enum import StrEnum
class PredefinedMessages(Enum):
class PredefinedMessages(StrEnum):
"""
Public. A dataclass with predetermined messages for quick use
"""
+3 -6
View File
@@ -201,9 +201,7 @@ class BaseApp:
return False
return True
def _error_handler(
self, error: BaseInputCommandException, raw_command: str
) -> None:
def _error_handler(self, error: BaseInputCommandException, raw_command: str) -> None:
"""
Private. Handles parsing errors of the entered command
:param error: error being handled
@@ -296,7 +294,7 @@ class BaseApp:
self._unknown_command_handler = unknown_command_handler
def _pre_cycle_setup(self) -> None:
def pre_cycle_setup(self) -> None:
"""
Private. Configures various aspects of the application before the start of the cycle
:return: None
@@ -330,7 +328,6 @@ class BaseApp:
self._print_func(message)
if self._messages_on_startup:
print("\n")
if not self._repeat_command_groups_description:
self._print_command_group_description()
@@ -381,7 +378,7 @@ class App(BaseApp):
Private. Starts the user input processing cycle
:return: None
"""
self._pre_cycle_setup()
self.pre_cycle_setup()
while True:
if self._repeat_command_groups_description:
self._print_command_group_description()
+4 -1
View File
@@ -1,4 +1,7 @@
__all__ = ["Flag", "InputFlag"]
__all__ = ["Flag", "InputFlag", "UndefinedInputFlags", "ValidInputFlags", "InvalidValueInputFlags", "Flags"]
from argenta.command.flag.models import Flag, InputFlag
from argenta.command.flag.flags.models import (UndefinedInputFlags,
ValidInputFlags, Flags,
InvalidValueInputFlags)
@@ -7,7 +7,7 @@ __all__ = [
]
from argenta.command.flags.models import (
from argenta.command.flag.flags.models import (
Flags,
InputFlags,
UndefinedInputFlags,
+1 -1
View File
@@ -1,5 +1,5 @@
from argenta.command.flag.models import Flag, InputFlag
from argenta.command.flags.models import InputFlags, Flags
from argenta.command.flag.flags.models import InputFlags, Flags
from argenta.command.exceptions import (
UnprocessedInputFlagException,
RepeatedInputFlagsException,
+4
View File
@@ -0,0 +1,4 @@
__all__ = ["get_time_of_pre_cycle_setup"]
from argenta.metrics.main import get_time_of_pre_cycle_setup
+26
View File
@@ -0,0 +1,26 @@
import io
from contextlib import redirect_stdout
from time import time
from argenta.router import Router
from argenta.command import Command
from argenta.response import Response
from argenta.response.status import Status
from argenta.command.flag import Flag, Flags
from argenta.app import App
def get_time_of_pre_cycle_setup(app: App) -> float:
start = time()
with redirect_stdout(io.StringIO()):
app.pre_cycle_setup()
end = time()
return end - start
+1 -1
View File
@@ -1,5 +1,5 @@
from argenta.response.status import Status
from argenta.command.flags import (
from argenta.command.flag.flags import (
ValidInputFlags,
UndefinedInputFlags,
InvalidValueInputFlags,
+1 -1
View File
@@ -6,7 +6,7 @@ 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.flags.models import (
from argenta.command.flag.flags import (
Flags,
InputFlags,
UndefinedInputFlags,