mirror of
https://github.com/koloideal/Argenta.git
synced 2026-06-10 10:05:28 +03:00
docs
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
from argenta import Orchestrator, App
|
||||
from argenta.orchestrator.argparser import BooleanArgument, ArgParser
|
||||
from argenta import App, Orchestrator
|
||||
from argenta.orchestrator.argparser import ArgParser, BooleanArgument
|
||||
|
||||
arg_parser = ArgParser(processed_args=[BooleanArgument('config')])
|
||||
orchestrator = Orchestrator(
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from argenta import Orchestrator, App
|
||||
from argenta import App, Orchestrator
|
||||
from argenta.orchestrator.argparser import ArgParser, ValueArgument
|
||||
|
||||
|
||||
# Определение аргументов приложения
|
||||
arguments = [
|
||||
ValueArgument(
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
from argenta import Router, Response
|
||||
from argenta import Response, Router
|
||||
from argenta.di import FromDishka
|
||||
from argenta.orchestrator.argparser import ArgSpace
|
||||
|
||||
|
||||
router = Router()
|
||||
|
||||
@router.command('get_args')
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
from argenta import Response, Router
|
||||
from argenta.di import FromDishka
|
||||
from argenta.orchestrator.argparser import (ArgSpace, BooleanArgument,
|
||||
ValueArgument)
|
||||
|
||||
router = Router()
|
||||
|
||||
@router.command('get_args')
|
||||
def get_args(response: Response, argspace: FromDishka[ArgSpace]):
|
||||
# Получение всех булевых флагов
|
||||
boolean_flags = argspace.get_by_type(BooleanArgument)
|
||||
print(f"Active flags: {[arg.name for arg in boolean_flags if arg.value]}")
|
||||
|
||||
# Получение всех аргументов со значениями
|
||||
value_args = argspace.get_by_type(ValueArgument)
|
||||
for arg in value_args:
|
||||
print(f"{arg.name} = {arg.value}")
|
||||
|
||||
# Подсчет количества аргументов каждого типа
|
||||
print(f"Boolean arguments: {len(argspace.get_by_type(BooleanArgument))}")
|
||||
print(f"Value arguments: {len(argspace.get_by_type(ValueArgument))}")
|
||||
@@ -0,0 +1,26 @@
|
||||
from argenta import Command
|
||||
from argenta.command import Flag, Flags
|
||||
|
||||
# Простая команда без флагов
|
||||
hello_cmd = Command(
|
||||
"hello",
|
||||
description="Greet the user"
|
||||
)
|
||||
|
||||
# Команда с описанием и псевдонимами
|
||||
quit_cmd = Command(
|
||||
"quit",
|
||||
description="Exit the application",
|
||||
aliases=["exit", "q"]
|
||||
)
|
||||
|
||||
# Команда с флагами
|
||||
deploy_cmd = Command(
|
||||
"deploy",
|
||||
description="Deploy application to server",
|
||||
flags=Flags([
|
||||
Flag("env", help="Environment name", possible_values=["dev", "prod"]),
|
||||
Flag("force", help="Force deployment")
|
||||
]),
|
||||
aliases=["dep"]
|
||||
)
|
||||
@@ -0,0 +1,18 @@
|
||||
from argenta import Router, Command, Response
|
||||
|
||||
router = Router(title="User Management")
|
||||
|
||||
@router.command(Command(
|
||||
"create-user",
|
||||
description="Create a new user account"
|
||||
))
|
||||
def handle_create_user(response):
|
||||
print("Creating new user...")
|
||||
|
||||
@router.command(Command(
|
||||
"delete-user",
|
||||
description="Delete existing user account",
|
||||
aliases=["remove-user", "rm-user"]
|
||||
))
|
||||
def handle_delete_user(response: Response):
|
||||
print("Deleting user...")
|
||||
@@ -0,0 +1,28 @@
|
||||
from argenta import Router, Command, Response
|
||||
from argenta.command import Flag, Flags
|
||||
|
||||
router = Router(title="Server Management")
|
||||
|
||||
@router.command(Command(
|
||||
"start",
|
||||
description="Start the server",
|
||||
flags=Flags([
|
||||
Flag("port", help="Server port", default="8080"),
|
||||
Flag("host", help="Server host", default="localhost"),
|
||||
Flag("debug", help="Enable debug mode")
|
||||
]),
|
||||
aliases=["run"]
|
||||
))
|
||||
def handle_start(response: Response):
|
||||
input_flags = response.input_flags
|
||||
port_flag = input_flags.get_flag_by_name("port")
|
||||
host_flag = input_flags.get_flag_by_name("host")
|
||||
debug_flag = input_flags.get_flag_by_name("debug")
|
||||
|
||||
host = host_flag.input_value if host_flag else "localhost"
|
||||
port = port_flag.input_value if port_flag else "8080"
|
||||
debug = debug_flag and debug_flag.input_value
|
||||
|
||||
print(f"Starting server on {host}:{port}")
|
||||
if debug:
|
||||
print("Debug mode: ON")
|
||||
@@ -0,0 +1,11 @@
|
||||
from argenta.command import InputCommand
|
||||
|
||||
# Парсинг команды без флагов
|
||||
cmd1 = InputCommand.parse("hello")
|
||||
print(cmd1.trigger) # "hello"
|
||||
print(len(cmd1.input_flags)) # 0
|
||||
|
||||
# Парсинг команды с флагами
|
||||
cmd2 = InputCommand.parse("deploy --env prod --force")
|
||||
print(cmd2.trigger) # "deploy"
|
||||
print(len(cmd2.input_flags)) # 2
|
||||
@@ -3,7 +3,6 @@ from sqlite3 import Connection
|
||||
from argenta import Response, Router
|
||||
from argenta.di import FromDishka
|
||||
|
||||
|
||||
router = Router()
|
||||
|
||||
@router.command('connect')
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from argenta import Response, Router
|
||||
from argenta.orchestrator.argparser import ArgSpace
|
||||
from argenta.di import FromDishka
|
||||
|
||||
from argenta.orchestrator.argparser import ArgSpace
|
||||
|
||||
router = Router()
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from argenta import App
|
||||
from argenta.app import StaticDividingLine, DynamicDividingLine
|
||||
from argenta.app import DynamicDividingLine, StaticDividingLine
|
||||
|
||||
# Создание статической линии из символов "=" длиной 40
|
||||
static_line = StaticDividingLine(unit_part="=", length=40)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from argenta import App
|
||||
|
||||
|
||||
def empty_command_handler():
|
||||
print("Empty command handler called")
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from argenta import App
|
||||
|
||||
|
||||
def incorrect_input_syntax_handler(raw_command: str):
|
||||
print(f"Incorrect input syntax for command: {raw_command}")
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from argenta import App
|
||||
|
||||
|
||||
def repeated_input_flags_handler(raw_command: str):
|
||||
print(f"Repeated input flags: {raw_command}")
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from argenta import App
|
||||
|
||||
|
||||
def empty_command_handler():
|
||||
print("Empty input command")
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from argenta import App
|
||||
from argenta.command import InputCommand
|
||||
|
||||
|
||||
def unknown_command_handler(command: InputCommand):
|
||||
print(f"Unknown input command with trigger: {command.trigger}")
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from argenta import App, Response
|
||||
|
||||
|
||||
def exit_command_handler(response: Response):
|
||||
print("Exit command handler")
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
from argenta.command import Flags, Flag
|
||||
from argenta import Command
|
||||
import re
|
||||
|
||||
|
||||
# Создание коллекции с флагами
|
||||
flags = Flags([
|
||||
Flag("host", possible_values=re.compile(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")),
|
||||
Flag("port", possible_values=re.compile(r"^\d{1,5}$"))
|
||||
])
|
||||
|
||||
# Использование в команде
|
||||
cmd = Command(
|
||||
"start",
|
||||
description="Start the server",
|
||||
flags=flags
|
||||
)
|
||||
@@ -1,5 +1,6 @@
|
||||
from argenta import App
|
||||
|
||||
|
||||
def custom_print_function(text: str) -> None:
|
||||
"""Простая пользовательская функция вывода с префиксом."""
|
||||
print(f"Префикс: {text}")
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
# main.py
|
||||
from argenta import App, Orchestrator
|
||||
from routers import router
|
||||
|
||||
from argenta import App, Orchestrator
|
||||
|
||||
app: App = App()
|
||||
orchestrator: Orchestrator = Orchestrator()
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# routers.py
|
||||
from argenta import Router, Response, Command
|
||||
from argenta import Command, Response, Router
|
||||
|
||||
router = Router(title="Quickstart Example")
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from argenta.router import Router
|
||||
from argenta.command import Command
|
||||
from argenta.router import Router
|
||||
|
||||
user_router = Router(title="User Management")
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
.. _root_api_command_flag:
|
||||
|
||||
Flag
|
||||
=====
|
||||
@@ -3,17 +3,225 @@
|
||||
Flags
|
||||
======
|
||||
|
||||
.. _root_api_command_flag:
|
||||
Объект ``Flags`` представляет собой коллекцию флагов команды в приложении ``Argenta``. Его основная задача — группировать и управлять набором флагов, зарегистрированных для конкретной команды. ``Flags`` служит контейнером, который позволяет удобно добавлять, извлекать и итерировать флаги, а также проверять их наличие.
|
||||
|
||||
Flag
|
||||
=====
|
||||
``Flags`` наследуется от базового класса ``BaseFlags`` и специализируется для работы с объектами типа ``Flag``. Этот класс используется при создании команд с множественными флагами и предоставляет интерфейс для управления ими.
|
||||
|
||||
.. seealso::
|
||||
|
||||
InputFlags
|
||||
===========
|
||||
Документация по отдельным флагам (:ref:`Flag <root_api_command_flag>`, :ref:`InputFlag <root_api_command_input_flag>`)
|
||||
|
||||
Документация по :ref:`InputFlags <root_api_command_input_flags>` — коллекции распаршенных флагов пользователя
|
||||
|
||||
.. _root_api_command_input_flag:
|
||||
:ref:`Общая информация <root_flags>` о флагах и их использовании в приложении ``Argenta``
|
||||
|
||||
InputFlag
|
||||
==========
|
||||
-----
|
||||
|
||||
Инициализация
|
||||
-------------
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
__init__(self, flags: list[Flag] | None = None) -> None
|
||||
|
||||
Создает новую коллекцию флагов.
|
||||
|
||||
* ``flags`` : Необязательный список флагов типа ``Flag`` для инициализации коллекции. Если не указан, создается пустая коллекция.
|
||||
|
||||
**Атрибуты:**
|
||||
|
||||
.. py:attribute:: flags
|
||||
|
||||
Список всех зарегистрированных флагов типа ``Flag``. Пустой список, если флаги не были переданы при инициализации.
|
||||
|
||||
**Пример использования:**
|
||||
|
||||
.. literalinclude:: ../../../code_snippets/flags_snippet.py
|
||||
:linenos:
|
||||
:language: python
|
||||
|
||||
-----
|
||||
|
||||
Методы
|
||||
------
|
||||
|
||||
add_flag
|
||||
~~~~~~~~
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
add_flag(self, flag: Flag) -> None
|
||||
|
||||
Добавляет один флаг в коллекцию.
|
||||
|
||||
:param flag: Флаг типа ``Flag`` для добавления в коллекцию
|
||||
:return: None
|
||||
|
||||
Метод добавляет переданный флаг в конец списка ``flags``. Используется для динамического расширения набора флагов после создания коллекции.
|
||||
|
||||
**Пример использования:**
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from argenta import Flags, ValueFlag, BooleanFlag
|
||||
|
||||
# Создание коллекции
|
||||
flags = Flags()
|
||||
|
||||
# Динамическое добавление флагов
|
||||
flags.add_flag(ValueFlag("config", help="Config file path"))
|
||||
flags.add_flag(BooleanFlag("debug", help="Debug mode"))
|
||||
flags.add_flag(ValueFlag("log-level", possible_values=["INFO", "DEBUG", "ERROR"]))
|
||||
|
||||
print(len(flags.flags)) # 3
|
||||
|
||||
-----
|
||||
|
||||
add_flags
|
||||
~~~~~~~~~
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
add_flags(self, flags: list[Flag]) -> None
|
||||
|
||||
Добавляет список флагов в коллекцию.
|
||||
|
||||
:param flags: Список флагов типа ``Flag`` для добавления
|
||||
:return: None
|
||||
|
||||
Метод расширяет текущую коллекцию, добавляя все флаги из переданного списка. Эффективен для пакетного добавления множества флагов.
|
||||
|
||||
**Пример использования:**
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from argenta import Flags, ValueFlag, BooleanFlag
|
||||
|
||||
# Начальная коллекция
|
||||
flags = Flags([
|
||||
ValueFlag("host", default="localhost")
|
||||
])
|
||||
|
||||
# Дополнительные флаги
|
||||
additional_flags = [
|
||||
ValueFlag("port", default="8080"),
|
||||
ValueFlag("database", help="Database name"),
|
||||
BooleanFlag("ssl", help="Use SSL"),
|
||||
BooleanFlag("verbose", help="Verbose output")
|
||||
]
|
||||
|
||||
# Добавление списка флагов
|
||||
flags.add_flags(additional_flags)
|
||||
|
||||
print(len(flags.flags)) # 5
|
||||
|
||||
-----
|
||||
|
||||
get_flag_by_name
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
get_flag_by_name(self, name: str) -> Flag | None
|
||||
|
||||
Получает флаг по его имени.
|
||||
|
||||
:param name: Имя искомого флага
|
||||
:return: Объект ``Flag`` с указанным именем или ``None``, если флаг не найден
|
||||
|
||||
Метод выполняет поиск по списку ``flags`` и возвращает первый флаг с соответствующим именем. Если флаг не найден, возвращается ``None``.
|
||||
|
||||
**Пример использования:**
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from argenta import Flags, ValueFlag, BooleanFlag
|
||||
|
||||
flags = Flags([
|
||||
ValueFlag("host", default="localhost"),
|
||||
ValueFlag("port", default="8080"),
|
||||
BooleanFlag("verbose")
|
||||
])
|
||||
|
||||
# Получение флага по имени
|
||||
host_flag = flags.get_flag_by_name("host")
|
||||
if host_flag:
|
||||
print(f"Found flag: {host_flag.name}")
|
||||
print(f"Default value: {host_flag.default}")
|
||||
|
||||
# Поиск несуществующего флага
|
||||
unknown_flag = flags.get_flag_by_name("nonexistent")
|
||||
if unknown_flag is None:
|
||||
print("Flag not found")
|
||||
|
||||
-----
|
||||
|
||||
Магические методы
|
||||
-----------------
|
||||
|
||||
__iter__
|
||||
~~~~~~~~
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
__iter__(self) -> Iterator[Flag]
|
||||
|
||||
Делает коллекцию итерируемой, позволяя использовать её в циклах.
|
||||
|
||||
:return: Итератор по списку флагов
|
||||
|
||||
**Пример использования:**
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from argenta import Flags, ValueFlag, BooleanFlag
|
||||
|
||||
flags = Flags([
|
||||
ValueFlag("host", default="localhost"),
|
||||
ValueFlag("port", default="8080"),
|
||||
BooleanFlag("verbose")
|
||||
])
|
||||
|
||||
# Итерация по всем флагам
|
||||
for flag in flags:
|
||||
print(f"Flag: {flag.name} (type: {type(flag).__name__})")
|
||||
|
||||
# Использование в list comprehension
|
||||
flag_names = [flag.name for flag in flags]
|
||||
print(f"All flags: {flag_names}")
|
||||
|
||||
-----
|
||||
|
||||
__getitem__
|
||||
~~~~~~~~~~~
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
__getitem__(self, flag_index: int) -> Flag
|
||||
|
||||
Позволяет получать флаги по индексу.
|
||||
|
||||
:param flag_index: Индекс флага в списке
|
||||
:return: Флаг с указанным индексом
|
||||
|
||||
**Пример использования:**
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from argenta import Flags, ValueFlag
|
||||
|
||||
flags = Flags([
|
||||
ValueFlag("first"),
|
||||
ValueFlag("second"),
|
||||
ValueFlag("third")
|
||||
|
||||
@@ -3,14 +3,145 @@
|
||||
Command
|
||||
=======
|
||||
|
||||
.. toctree::
|
||||
:hidden:
|
||||
Объект ``Command`` представляет собой основную единицу функциональности в приложении ``Argenta``. Каждая команда определяет конкретное действие, которое пользователь может выполнить, введя соответствующий триггер. Команды регистрируются в роутерах и образуют интерфейс взаимодействия с приложением.
|
||||
|
||||
flags
|
||||
possible_values
|
||||
validation_status
|
||||
``Command`` инкапсулирует всю необходимую информацию о команде: её триггер (ключевое слово для вызова), описание, набор флагов для настройки поведения и список псевдонимов для альтернативных способов вызова.
|
||||
|
||||
.. _input_command:
|
||||
-----
|
||||
|
||||
Инициализация
|
||||
-------------
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
__init__(self, trigger: str, *,
|
||||
description: str | None = None,
|
||||
flags: Flag | Flags = DEFAULT_WITHOUT_FLAGS,
|
||||
aliases: list[str] | None = None) -> None
|
||||
|
||||
Создает новую команду для регистрации в роутере.
|
||||
|
||||
* ``trigger`` : Строковый триггер команды, который пользователь должен ввести для её вызова. Это основной идентификатор команды в системе.
|
||||
|
||||
* ``description`` : Необязательное описание команды, объясняющее её назначение. Если не указано, используется значение по умолчанию ``"Command without description"``. Отображается в справке и списке доступных команд.
|
||||
|
||||
* ``flags`` : Набор флагов команды для настройки её поведения. Может быть одиночным объектом ``Flag`` или коллекцией ``Flags``. По умолчанию команда создается без флагов.
|
||||
|
||||
* ``aliases`` : Список строковых синонимов для основного триггера. Позволяет вызывать команду альтернативными способами. По умолчанию список пуст.
|
||||
|
||||
**Атрибуты:**
|
||||
|
||||
.. py:attribute:: trigger
|
||||
|
||||
Основной триггер команды в виде строки. Используется для идентификации команды при парсинге пользовательского ввода.
|
||||
|
||||
.. py:attribute:: description
|
||||
|
||||
Текстовое описание команды. Если не было передано при инициализации, содержит значение ``"Command without description"``.
|
||||
|
||||
.. py:attribute:: registered_flags
|
||||
|
||||
Объект ``Flags``, содержащий все зарегистрированные флаги команды. Автоматически конвертируется из одиночного ``Flag`` в коллекцию при инициализации.
|
||||
|
||||
.. py:attribute:: aliases
|
||||
|
||||
Список строк с альтернативными триггерами команды. Пустой список, если псевдонимы не заданы.
|
||||
|
||||
**Пример использования:**
|
||||
|
||||
.. literalinclude:: ../../../code_snippets/command_snippet.py
|
||||
:linenos:
|
||||
|
||||
.. seealso ::
|
||||
Подробнее про флаги: :ref:`Flags <root_api_command_flags>` и :ref:`Флаги вводимых команд <root_flags>`.
|
||||
|
||||
-----
|
||||
|
||||
Регистрация команд
|
||||
------------------
|
||||
|
||||
Команды регистрируются в роутерах с помощью декоратора ``@router.command()``. После регистрации команда становится доступной пользователям для вызова.
|
||||
|
||||
**Базовый пример:**
|
||||
|
||||
.. literalinclude:: ../../../code_snippets/command_snippet2.py
|
||||
:linenos:
|
||||
|
||||
**Команды с флагами:**
|
||||
|
||||
.. literalinclude:: ../../../code_snippets/command_snippet3.py
|
||||
:linenos:
|
||||
|
||||
-----
|
||||
|
||||
Работа с псевдонимами
|
||||
---------------------
|
||||
|
||||
Псевдонимы позволяют вызывать один и тот же хэндлер разными триггерами, сохраняя при этом флаги команды и описание.
|
||||
|
||||
**Пример с псевдонимами:**
|
||||
|
||||
.. code-block:: python
|
||||
:linenos:
|
||||
|
||||
from argenta import Router, Command
|
||||
|
||||
router = Router(title="System")
|
||||
|
||||
@router.command(Command(
|
||||
"shutdown",
|
||||
description="Shutdown the system",
|
||||
aliases=["poweroff", "halt", "stop"]
|
||||
))
|
||||
def handle_shutdown(response):
|
||||
response.write("Shutting down the system...")
|
||||
|
||||
Теперь пользователь может вызвать команду любым из способов:
|
||||
|
||||
.. code-block:: bash
|
||||
|
||||
shutdown
|
||||
poweroff
|
||||
halt
|
||||
stop
|
||||
|
||||
Все эти варианты выполнят одну и ту же функцию ``handle_shutdown``.
|
||||
|
||||
-----
|
||||
|
||||
.. _root_api_command_input_command:
|
||||
|
||||
InputCommand
|
||||
~~~~~~~~~~~~
|
||||
------------
|
||||
|
||||
Класс ``InputCommand`` представляет собой распаршенную команду, введенную пользователем. Это внутренний класс, который создается автоматически при парсинге пользовательского ввода. Непосредственная работа с данным классом возможна при создании кастомного хэндлера для обработки неизвестных команд.
|
||||
|
||||
.. seealso ::
|
||||
Подробнее про кастомные хэндлеры обработки исключений ввода :ref:`тут <root_error_handling>`
|
||||
|
||||
Создает экземпляр распарсенной команды.
|
||||
|
||||
:param trigger: Триггер команды, извлеченный из пользовательского ввода
|
||||
:param input_flags: Флаги, переданные пользователем при вызове команды
|
||||
|
||||
**Атрибуты:**
|
||||
|
||||
.. py:attribute:: trigger
|
||||
:no-index:
|
||||
|
||||
Строковый триггер команды, введенный пользователем.
|
||||
|
||||
.. py:attribute:: input_flags
|
||||
|
||||
Объект ``InputFlags``, содержащий все флаги, переданные с командой. Автоматически конвертируется из одиночного ``InputFlag`` в коллекцию.
|
||||
|
||||
.. toctree ::
|
||||
:hidden:
|
||||
|
||||
flag
|
||||
possible_values
|
||||
input_flag
|
||||
validation_status
|
||||
flags
|
||||
input_flags
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
.. _root_api_command_input_flag:
|
||||
|
||||
InputFlag
|
||||
==========
|
||||
|
||||
Объект ``InputFlag`` представляет собой флаг команды, который принимает значение ввода от пользователя. Он наследуется от базового класса ``Flag`` и расширяет его функциональность, добавляя возможность указания типа ввода и обработки введенных данных.
|
||||
@@ -0,0 +1,4 @@
|
||||
.. _root_api_command_input_flags:
|
||||
|
||||
InputFlags
|
||||
===========
|
||||
@@ -85,24 +85,9 @@ get_by_type
|
||||
|
||||
**Пример использования:**
|
||||
|
||||
.. code-block:: python
|
||||
.. literalinclude:: ../../../code_snippets/argspace_snippet3.py
|
||||
:linenos:
|
||||
|
||||
from argenta import BooleanArgument, ValueArgument
|
||||
|
||||
# Получение всех булевых флагов
|
||||
boolean_flags = argspace.get_by_type(BooleanArgument)
|
||||
print(f"Active flags: {[arg.name for arg in boolean_flags if arg.value]}")
|
||||
|
||||
# Получение всех аргументов со значениями
|
||||
value_args = argspace.get_by_type(ValueArgument)
|
||||
for arg in value_args:
|
||||
print(f"{arg.name} = {arg.value}")
|
||||
|
||||
# Подсчет количества аргументов каждого типа
|
||||
print(f"Boolean arguments: {len(argspace.get_by_type(BooleanArgument))}")
|
||||
print(f"Value arguments: {len(argspace.get_by_type(ValueArgument))}")
|
||||
|
||||
-----
|
||||
|
||||
InputArgument
|
||||
|
||||
@@ -116,7 +116,7 @@
|
||||
|
||||
Для переопределения стандартного поведения используется сеттер ``.set_unknown_command_handler(_: NonStandardBehaviorHandler[InputCommand])``,
|
||||
протокол ``NonStandardBehaviorHandler[InputCommand]`` соответствует ``Callable[[InputCommand], None]``, то есть хэндлер должен быть вызываемым объектом,
|
||||
к примеру функция или лямбда, которая принимает обязательный аргумент типа :ref:`InputCommand <input_command>` и ничего не возвращает.
|
||||
к примеру функция или лямбда, которая принимает обязательный аргумент типа :ref:`InputCommand <root_api_command_input_command>` и ничего не возвращает.
|
||||
|
||||
Сэмпл кода, переопределяющего хэндлер ввода неизвестной команды:
|
||||
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
from argenta.app import App
|
||||
from argenta.command import Command
|
||||
from argenta.metrics import get_time_of_pre_cycle_setup
|
||||
from argenta.response import Response
|
||||
from argenta.router import Router
|
||||
from argenta.app import App
|
||||
|
||||
|
||||
|
||||
def commands_with_two_aliases(num_of_commands: int):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# main.py
|
||||
from argenta import App, Orchestrator
|
||||
|
||||
from .routers import router
|
||||
|
||||
app: App = App()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# routers.py
|
||||
from argenta import Router, Response, Command
|
||||
from argenta import Command, Response, Router
|
||||
|
||||
router = Router(title="Quickstart Example")
|
||||
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
from mock.mock_app.routers import work_router
|
||||
|
||||
from argenta import App, Orchestrator
|
||||
from argenta.app import PredefinedMessages, DynamicDividingLine, AutoCompleter
|
||||
from argenta.app import AutoCompleter, DynamicDividingLine, PredefinedMessages
|
||||
from argenta.orchestrator import ArgParser
|
||||
from argenta.orchestrator.argparser import BooleanArgument, ValueArgument
|
||||
|
||||
from mock.mock_app.routers import work_router
|
||||
|
||||
arg_parser: ArgParser = ArgParser(
|
||||
processed_args=[
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
from dishka import FromDishka
|
||||
|
||||
from argenta import Router
|
||||
from argenta.command import Flag, PossibleValues
|
||||
from argenta.orchestrator.argparser import ArgSpace
|
||||
from argenta.response import Response
|
||||
from argenta import Router
|
||||
from argenta.router.defaults import system_router
|
||||
from dishka import FromDishka
|
||||
|
||||
|
||||
work_router: Router = Router(title="Work points:")
|
||||
|
||||
|
||||
+1
-1
@@ -45,7 +45,7 @@ exclude = [
|
||||
]
|
||||
|
||||
[tool.pyright]
|
||||
typeCheckingMode = "standard"
|
||||
typeCheckingMode = "strict"
|
||||
|
||||
[tool.mypy]
|
||||
disable_error_code = "import-untyped"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
from argenta.app.models import App as App
|
||||
from argenta.orchestrator.entity import Orchestrator as Orchestrator
|
||||
from argenta.router.entity import Router as Router
|
||||
from argenta.response.entity import Response as Response
|
||||
from argenta.command.models import Command as Command
|
||||
from argenta.orchestrator.entity import Orchestrator as Orchestrator
|
||||
from argenta.response.entity import Response as Response
|
||||
from argenta.router.entity import Router as Router
|
||||
|
||||
@@ -5,7 +5,8 @@ import re
|
||||
from contextlib import redirect_stdout
|
||||
from typing import Never, TypeAlias
|
||||
|
||||
from art import text2art # pyright: ignore[reportMissingTypeStubs, reportUnknownVariableType]
|
||||
from art import \
|
||||
text2art # pyright: ignore[reportMissingTypeStubs, reportUnknownVariableType]
|
||||
from rich.console import Console
|
||||
from rich.markup import escape
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
from argenta.command.flag import (Flag as Flag,
|
||||
Flags as Flags,
|
||||
InputFlag as InputFlag,
|
||||
InputFlags as InputFlags,
|
||||
PossibleValues as PossibleValues)
|
||||
from argenta.command.flag import Flag as Flag
|
||||
from argenta.command.flag import Flags as Flags
|
||||
from argenta.command.flag import InputFlag as InputFlag
|
||||
from argenta.command.flag import InputFlags as InputFlags
|
||||
from argenta.command.flag import PossibleValues as PossibleValues
|
||||
from argenta.command.flag.defaults import PredefinedFlags as PredefinedFlags
|
||||
from argenta.command.models import (Command as Command,
|
||||
InputCommand as InputCommand)
|
||||
from argenta.command.models import Command as Command
|
||||
from argenta.command.models import InputCommand as InputCommand
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
from argenta.command.flag.flags.models import (Flags as Flags,
|
||||
InputFlags as InputFlags)
|
||||
from argenta.command.flag.models import (Flag as Flag,
|
||||
InputFlag as InputFlag)
|
||||
from argenta.command.flag.models import (PossibleValues as PossibleValues,
|
||||
ValidationStatus as ValidationStatus)
|
||||
from argenta.command.flag.flags.models import Flags as Flags
|
||||
from argenta.command.flag.flags.models import InputFlags as InputFlags
|
||||
from argenta.command.flag.models import Flag as Flag
|
||||
from argenta.command.flag.models import InputFlag as InputFlag
|
||||
from argenta.command.flag.models import PossibleValues as PossibleValues
|
||||
from argenta.command.flag.models import ValidationStatus as ValidationStatus
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import _io
|
||||
from unittest.mock import patch, MagicMock
|
||||
from unittest import TestCase
|
||||
import io
|
||||
import re
|
||||
import sys
|
||||
from unittest import TestCase
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import _io
|
||||
|
||||
from argenta import App, Orchestrator, Router
|
||||
from argenta.command import Command, PredefinedFlags
|
||||
from argenta.command.flag.models import ValidationStatus
|
||||
from argenta.command.flag.flags.models import Flags
|
||||
from argenta import Orchestrator, App, Router
|
||||
from argenta.command.flag.models import ValidationStatus
|
||||
from argenta.response import Response
|
||||
|
||||
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import _io
|
||||
from unittest.mock import patch, MagicMock
|
||||
from unittest import TestCase
|
||||
import io
|
||||
import re
|
||||
import sys
|
||||
from unittest import TestCase
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import _io
|
||||
|
||||
from argenta import App, Orchestrator, Router
|
||||
from argenta.command import Command, PredefinedFlags
|
||||
from argenta.command.flag.models import PossibleValues, ValidationStatus
|
||||
from argenta.response import Response
|
||||
from argenta import Orchestrator, App, Router
|
||||
from argenta.command.flag import Flag
|
||||
from argenta.command.flag.flags import Flags
|
||||
from argenta.command.flag.models import PossibleValues, ValidationStatus
|
||||
from argenta.response import Response
|
||||
|
||||
|
||||
class PatchedArgvTestCase(TestCase):
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
from argenta.command.models import InputCommand, Command
|
||||
from argenta.app import App
|
||||
|
||||
import unittest
|
||||
|
||||
from argenta.app import App
|
||||
from argenta.command.models import Command, InputCommand
|
||||
from argenta.router import Router
|
||||
|
||||
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import pytest
|
||||
from argparse import Namespace
|
||||
from unittest.mock import MagicMock, call
|
||||
|
||||
from argenta.orchestrator.argparser.entity import ArgParser, ArgSpace
|
||||
from argenta.orchestrator.argparser.arguments.models import (
|
||||
ValueArgument,
|
||||
import pytest
|
||||
|
||||
from argenta.orchestrator.argparser.arguments.models import (BaseArgument,
|
||||
BooleanArgument,
|
||||
InputArgument,
|
||||
BaseArgument,
|
||||
)
|
||||
ValueArgument)
|
||||
from argenta.orchestrator.argparser.entity import ArgParser, ArgSpace
|
||||
|
||||
|
||||
class TestArgumentCreation:
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch, call
|
||||
from unittest.mock import MagicMock, call, patch
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -46,7 +46,9 @@ def mock_readline():
|
||||
|
||||
# We import the class under test after setting up the patch context if needed,
|
||||
# or ensure patches target the correct import location.
|
||||
from argenta.app.autocompleter.entity import AutoCompleter, _get_history_items, _is_command_exist
|
||||
from argenta.app.autocompleter.entity import (AutoCompleter,
|
||||
_get_history_items,
|
||||
_is_command_exist)
|
||||
|
||||
|
||||
class TestAutoCompleter:
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import re
|
||||
import unittest
|
||||
|
||||
from argenta.command.exceptions import (EmptyInputCommandException,
|
||||
RepeatedInputFlagsException,
|
||||
UnprocessedInputFlagException)
|
||||
from argenta.command.flag import Flag, InputFlag
|
||||
from argenta.command.flag.flags import Flags
|
||||
from argenta.command.flag.models import PossibleValues
|
||||
from argenta.command.models import InputCommand, Command, ValidationStatus
|
||||
from argenta.command.exceptions import (UnprocessedInputFlagException,
|
||||
RepeatedInputFlagsException,
|
||||
EmptyInputCommandException)
|
||||
|
||||
import unittest
|
||||
import re
|
||||
from argenta.command.models import Command, InputCommand, ValidationStatus
|
||||
|
||||
|
||||
class TestInputCommand(unittest.TestCase):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from argenta.app.dividing_line import DynamicDividingLine, StaticDividingLine
|
||||
|
||||
import unittest
|
||||
|
||||
from argenta.app.dividing_line import DynamicDividingLine, StaticDividingLine
|
||||
|
||||
|
||||
class TestDividingLine(unittest.TestCase):
|
||||
def test_get_static_dividing_line_full_line(self):
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
from argenta.command.flag import Flag, InputFlag, PossibleValues
|
||||
from argenta.command.flag.flags import InputFlags, Flags
|
||||
|
||||
import unittest
|
||||
import re
|
||||
import unittest
|
||||
|
||||
from argenta.command.flag import Flag, InputFlag, PossibleValues
|
||||
from argenta.command.flag.flags import Flags, InputFlags
|
||||
|
||||
|
||||
class TestFlag(unittest.TestCase):
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import unittest
|
||||
from datetime import datetime, date
|
||||
from datetime import date, datetime
|
||||
|
||||
from argenta.response.entity import Response, DataBridge, EMPTY_INPUT_FLAGS
|
||||
from argenta.response.status import ResponseStatus
|
||||
from argenta.command.flag.flags.models import InputFlags
|
||||
from argenta.command.flag import InputFlag
|
||||
from argenta.command.flag.flags.models import InputFlags
|
||||
from argenta.response.entity import EMPTY_INPUT_FLAGS, DataBridge, Response
|
||||
from argenta.response.status import ResponseStatus
|
||||
|
||||
|
||||
class TestDataBridge(unittest.TestCase):
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
from argenta.command.flag import InputFlag, Flag
|
||||
import re
|
||||
import unittest
|
||||
|
||||
from argenta.command import Command
|
||||
from argenta.command.flag import Flag, InputFlag
|
||||
from argenta.command.flag.flags import Flags, InputFlags
|
||||
from argenta.command.flag.models import PossibleValues, ValidationStatus
|
||||
from argenta.response.entity import Response
|
||||
from argenta.router import Router
|
||||
from argenta.command import Command
|
||||
from argenta.router.entity import _structuring_input_flags, _validate_command, _validate_func_args # pyright: ignore[reportPrivateUsage]
|
||||
from argenta.router.exceptions import (TriggerContainSpacesException,
|
||||
RepeatedFlagNameException,
|
||||
RequiredArgumentNotPassedException)
|
||||
|
||||
import unittest
|
||||
import re
|
||||
from argenta.router.entity import ( # pyright: ignore[reportPrivateUsage]
|
||||
_structuring_input_flags, _validate_command, _validate_func_args)
|
||||
from argenta.router.exceptions import (RepeatedFlagNameException,
|
||||
RequiredArgumentNotPassedException,
|
||||
TriggerContainSpacesException)
|
||||
|
||||
|
||||
class TestRouter(unittest.TestCase):
|
||||
|
||||
Reference in New Issue
Block a user