mirror of
https://github.com/koloideal/Argenta.git
synced 2026-06-10 18:15:28 +03:00
docs
This commit is contained in:
@@ -1,7 +1,7 @@
|
|||||||
from argenta import App, Orchestrator
|
from argenta import App, Orchestrator
|
||||||
from argenta.orchestrator.argparser import ArgParser, BooleanArgument
|
from argenta.orchestrator.argparser import ArgParser, BooleanArgument
|
||||||
|
|
||||||
arg_parser = ArgParser(processed_args=[BooleanArgument('config')])
|
arg_parser = ArgParser(processed_args=[BooleanArgument("config")])
|
||||||
orchestrator = Orchestrator(
|
orchestrator = Orchestrator(
|
||||||
arg_parser=arg_parser,
|
arg_parser=arg_parser,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -3,23 +3,13 @@ from argenta.orchestrator.argparser import ArgParser, ValueArgument
|
|||||||
|
|
||||||
# Определение аргументов приложения
|
# Определение аргументов приложения
|
||||||
arguments = [
|
arguments = [
|
||||||
ValueArgument(
|
ValueArgument("host", help="Server host", default="localhost"),
|
||||||
"host",
|
ValueArgument("port", help="Server port", default="8080"),
|
||||||
help="Server host",
|
|
||||||
default="localhost"
|
|
||||||
),
|
|
||||||
ValueArgument(
|
|
||||||
"port",
|
|
||||||
help="Server port",
|
|
||||||
default="8080"
|
|
||||||
),
|
|
||||||
]
|
]
|
||||||
|
|
||||||
# Создание и запуск парсера
|
# Создание и запуск парсера
|
||||||
argparser = ArgParser(
|
argparser = ArgParser(
|
||||||
processed_args=arguments,
|
processed_args=arguments, name="WebServer", description="Simple web server"
|
||||||
name="WebServer",
|
|
||||||
description="Simple web server"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
app = App()
|
app = App()
|
||||||
@@ -40,6 +30,6 @@ def main():
|
|||||||
|
|
||||||
orchestrator.start_polling(app)
|
orchestrator.start_polling(app)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
|
||||||
@@ -4,7 +4,7 @@ from argenta.orchestrator.argparser import ArgSpace
|
|||||||
|
|
||||||
router = Router()
|
router = Router()
|
||||||
|
|
||||||
@router.command('get_args')
|
|
||||||
|
@router.command("get_args")
|
||||||
async def get_args(response: Response, argspace: FromDishka[ArgSpace]):
|
async def get_args(response: Response, argspace: FromDishka[ArgSpace]):
|
||||||
print(argspace.all_arguments)
|
print(argspace.all_arguments)
|
||||||
|
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
from argenta import Response, Router
|
from argenta import Response, Router
|
||||||
from argenta.di import FromDishka
|
from argenta.di import FromDishka
|
||||||
from argenta.orchestrator.argparser import (ArgSpace, BooleanArgument,
|
from argenta.orchestrator.argparser import ArgSpace, BooleanArgument, ValueArgument
|
||||||
ValueArgument)
|
|
||||||
|
|
||||||
router = Router()
|
router = Router()
|
||||||
|
|
||||||
@router.command('get_args')
|
|
||||||
|
@router.command("get_args")
|
||||||
def get_args(response: Response, argspace: FromDishka[ArgSpace]):
|
def get_args(response: Response, argspace: FromDishka[ArgSpace]):
|
||||||
# Получение всех булевых флагов
|
# Получение всех булевых флагов
|
||||||
boolean_flags = argspace.get_by_type(BooleanArgument)
|
boolean_flags = argspace.get_by_type(BooleanArgument)
|
||||||
|
|||||||
@@ -2,25 +2,20 @@ from argenta import Command
|
|||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
# Простая команда без флагов
|
# Простая команда без флагов
|
||||||
hello_cmd = Command(
|
hello_cmd = Command("hello", description="Greet the user")
|
||||||
"hello",
|
|
||||||
description="Greet the user"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Команда с описанием и псевдонимами
|
# Команда с описанием и псевдонимами
|
||||||
quit_cmd = Command(
|
quit_cmd = Command("quit", description="Exit the application", aliases=["exit", "q"])
|
||||||
"quit",
|
|
||||||
description="Exit the application",
|
|
||||||
aliases=["exit", "q"]
|
|
||||||
)
|
|
||||||
|
|
||||||
# Команда с флагами
|
# Команда с флагами
|
||||||
deploy_cmd = Command(
|
deploy_cmd = Command(
|
||||||
"deploy",
|
"deploy",
|
||||||
description="Deploy application to server",
|
description="Deploy application to server",
|
||||||
flags=Flags([
|
flags=Flags(
|
||||||
Flag("env", help="Environment name", possible_values=["dev", "prod"]),
|
[
|
||||||
Flag("force", help="Force deployment")
|
Flag("env", help="Environment name", possible_values=["dev", "prod"]),
|
||||||
]),
|
Flag("force", help="Force deployment"),
|
||||||
aliases=["dep"]
|
]
|
||||||
|
),
|
||||||
|
aliases=["dep"],
|
||||||
)
|
)
|
||||||
@@ -2,17 +2,18 @@ from argenta import Command, Response, Router
|
|||||||
|
|
||||||
router = Router(title="User Management")
|
router = Router(title="User Management")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"create-user",
|
@router.command(Command("create-user", description="Create a new user account"))
|
||||||
description="Create a new user account"
|
|
||||||
))
|
|
||||||
def handle_create_user(response):
|
def handle_create_user(response):
|
||||||
print("Creating new user...")
|
print("Creating new user...")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"delete-user",
|
@router.command(
|
||||||
description="Delete existing user account",
|
Command(
|
||||||
aliases=["remove-user", "rm-user"]
|
"delete-user",
|
||||||
))
|
description="Delete existing user account",
|
||||||
|
aliases=["remove-user", "rm-user"],
|
||||||
|
)
|
||||||
|
)
|
||||||
def handle_delete_user(response: Response):
|
def handle_delete_user(response: Response):
|
||||||
print("Deleting user...")
|
print("Deleting user...")
|
||||||
@@ -3,16 +3,21 @@ from argenta.command import Flag, Flags
|
|||||||
|
|
||||||
router = Router(title="Server Management")
|
router = Router(title="Server Management")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"start",
|
@router.command(
|
||||||
description="Start the server",
|
Command(
|
||||||
flags=Flags([
|
"start",
|
||||||
Flag("port", help="Server port", default="8080"),
|
description="Start the server",
|
||||||
Flag("host", help="Server host", default="localhost"),
|
flags=Flags(
|
||||||
Flag("debug", help="Enable debug mode")
|
[
|
||||||
]),
|
Flag("port", help="Server port", default="8080"),
|
||||||
aliases=["run"]
|
Flag("host", help="Server host", default="localhost"),
|
||||||
))
|
Flag("debug", help="Enable debug mode"),
|
||||||
|
]
|
||||||
|
),
|
||||||
|
aliases=["run"],
|
||||||
|
)
|
||||||
|
)
|
||||||
def handle_start(response: Response):
|
def handle_start(response: Response):
|
||||||
input_flags = response.input_flags
|
input_flags = response.input_flags
|
||||||
port_flag = input_flags.get_flag_by_name("port")
|
port_flag = input_flags.get_flag_by_name("port")
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from argenta.di import FromDishka
|
|||||||
|
|
||||||
router = Router()
|
router = Router()
|
||||||
|
|
||||||
@router.command('connect')
|
|
||||||
def connect_handler(response: Response, connection: FromDishka[Connection]):
|
|
||||||
connection.execute('...')
|
|
||||||
|
|
||||||
|
@router.command("connect")
|
||||||
|
def connect_handler(response: Response, connection: FromDishka[Connection]):
|
||||||
|
connection.execute("...")
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from argenta.orchestrator.argparser import ArgSpace
|
|||||||
|
|
||||||
router = Router()
|
router = Router()
|
||||||
|
|
||||||
@router.command('info')
|
|
||||||
def connect_handler(response: Response, argspace: FromDishka[ArgSpace]):
|
|
||||||
print(argspace.get_by_name('type'))
|
|
||||||
|
|
||||||
|
@router.command("info")
|
||||||
|
def connect_handler(response: Response, argspace: FromDishka[ArgSpace]):
|
||||||
|
print(argspace.get_by_name("type"))
|
||||||
|
|||||||
@@ -4,5 +4,6 @@ from argenta import App
|
|||||||
def empty_command_handler():
|
def empty_command_handler():
|
||||||
print("Empty command handler called")
|
print("Empty command handler called")
|
||||||
|
|
||||||
|
|
||||||
app: App = App()
|
app: App = App()
|
||||||
app.set_empty_command_handler(empty_command_handler)
|
app.set_empty_command_handler(empty_command_handler)
|
||||||
|
|||||||
@@ -4,5 +4,6 @@ from argenta import App
|
|||||||
def incorrect_input_syntax_handler(raw_command: str):
|
def incorrect_input_syntax_handler(raw_command: str):
|
||||||
print(f"Incorrect input syntax for command: {raw_command}")
|
print(f"Incorrect input syntax for command: {raw_command}")
|
||||||
|
|
||||||
|
|
||||||
app: App = App()
|
app: App = App()
|
||||||
app.set_incorrect_input_syntax_handler(incorrect_input_syntax_handler)
|
app.set_incorrect_input_syntax_handler(incorrect_input_syntax_handler)
|
||||||
|
|||||||
@@ -4,5 +4,6 @@ from argenta import App
|
|||||||
def repeated_input_flags_handler(raw_command: str):
|
def repeated_input_flags_handler(raw_command: str):
|
||||||
print(f"Repeated input flags: {raw_command}")
|
print(f"Repeated input flags: {raw_command}")
|
||||||
|
|
||||||
|
|
||||||
app: App = App()
|
app: App = App()
|
||||||
app.set_repeated_input_flags_handler(repeated_input_flags_handler)
|
app.set_repeated_input_flags_handler(repeated_input_flags_handler)
|
||||||
|
|||||||
@@ -4,5 +4,6 @@ from argenta import App
|
|||||||
def empty_command_handler():
|
def empty_command_handler():
|
||||||
print("Empty input command")
|
print("Empty input command")
|
||||||
|
|
||||||
|
|
||||||
app: App = App()
|
app: App = App()
|
||||||
app.set_empty_command_handler(empty_command_handler)
|
app.set_empty_command_handler(empty_command_handler)
|
||||||
|
|||||||
@@ -5,5 +5,6 @@ from argenta.command import InputCommand
|
|||||||
def unknown_command_handler(command: InputCommand):
|
def unknown_command_handler(command: InputCommand):
|
||||||
print(f"Unknown input command with trigger: {command.trigger}")
|
print(f"Unknown input command with trigger: {command.trigger}")
|
||||||
|
|
||||||
|
|
||||||
app: App = App()
|
app: App = App()
|
||||||
app.set_unknown_command_handler(unknown_command_handler)
|
app.set_unknown_command_handler(unknown_command_handler)
|
||||||
|
|||||||
@@ -4,5 +4,6 @@ from argenta import App, Response
|
|||||||
def exit_command_handler(response: Response):
|
def exit_command_handler(response: Response):
|
||||||
print("Exit command handler")
|
print("Exit command handler")
|
||||||
|
|
||||||
|
|
||||||
app: App = App()
|
app: App = App()
|
||||||
app.set_exit_command_handler(exit_command_handler)
|
app.set_exit_command_handler(exit_command_handler)
|
||||||
|
|||||||
@@ -2,32 +2,36 @@ from argenta.command import Flags
|
|||||||
from argenta.command.flag.defaults import PredefinedFlags
|
from argenta.command.flag.defaults import PredefinedFlags
|
||||||
|
|
||||||
# Использование предопределенных флагов при создании команды
|
# Использование предопределенных флагов при создании команды
|
||||||
command_flags = Flags([
|
command_flags = Flags(
|
||||||
PredefinedFlags.HELP,
|
[
|
||||||
PredefinedFlags.SHORT_HELP,
|
PredefinedFlags.HELP,
|
||||||
PredefinedFlags.INFO,
|
PredefinedFlags.SHORT_HELP,
|
||||||
])
|
PredefinedFlags.INFO,
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
# Использование сетевых флагов
|
# Использование сетевых флагов
|
||||||
network_flags = Flags([
|
network_flags = Flags(
|
||||||
PredefinedFlags.HOST,
|
[
|
||||||
PredefinedFlags.PORT,
|
PredefinedFlags.HOST,
|
||||||
])
|
PredefinedFlags.PORT,
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
# Валидация значений предопределенных флагов
|
# Валидация значений предопределенных флагов
|
||||||
print(PredefinedFlags.HOST.validate_input_flag_value("192.168.1.1")) # True
|
print(PredefinedFlags.HOST.validate_input_flag_value("192.168.1.1")) # True
|
||||||
print(PredefinedFlags.HOST.validate_input_flag_value("invalid")) # False
|
print(PredefinedFlags.HOST.validate_input_flag_value("invalid")) # False
|
||||||
|
|
||||||
print(PredefinedFlags.PORT.validate_input_flag_value("8080")) # True
|
print(PredefinedFlags.PORT.validate_input_flag_value("8080")) # True
|
||||||
print(PredefinedFlags.PORT.validate_input_flag_value("99999")) # True
|
print(PredefinedFlags.PORT.validate_input_flag_value("99999")) # True
|
||||||
print(PredefinedFlags.PORT.validate_input_flag_value("abc")) # False
|
print(PredefinedFlags.PORT.validate_input_flag_value("abc")) # False
|
||||||
|
|
||||||
# Флаги без значений
|
# Флаги без значений
|
||||||
print(PredefinedFlags.HELP.validate_input_flag_value(None)) # True
|
print(PredefinedFlags.HELP.validate_input_flag_value(None)) # True
|
||||||
print(PredefinedFlags.HELP.validate_input_flag_value("something")) # False
|
print(PredefinedFlags.HELP.validate_input_flag_value("something")) # False
|
||||||
|
|
||||||
# Проверка строковых представлений
|
# Проверка строковых представлений
|
||||||
print(PredefinedFlags.HELP.string_entity) # --help
|
print(PredefinedFlags.HELP.string_entity) # --help
|
||||||
print(PredefinedFlags.SHORT_HELP.string_entity) # -H
|
print(PredefinedFlags.SHORT_HELP.string_entity) # -H
|
||||||
print(PredefinedFlags.HOST.string_entity) # --host
|
print(PredefinedFlags.HOST.string_entity) # --host
|
||||||
print(PredefinedFlags.SHORT_PORT.string_entity) # -P
|
print(PredefinedFlags.SHORT_PORT.string_entity) # -P
|
||||||
|
|||||||
@@ -12,13 +12,10 @@ short_flag = Flag(name="v", prefix="-")
|
|||||||
help_flag = Flag(name="help", possible_values=PossibleValues.NEITHER)
|
help_flag = Flag(name="help", possible_values=PossibleValues.NEITHER)
|
||||||
|
|
||||||
# Флаг со списком допустимых значений
|
# Флаг со списком допустимых значений
|
||||||
format_flag = Flag(
|
format_flag = Flag(name="format", possible_values=["json", "xml", "csv"])
|
||||||
name="format",
|
|
||||||
possible_values=["json", "xml", "csv"]
|
|
||||||
)
|
|
||||||
|
|
||||||
# Флаг с регулярным выражением для валидации
|
# Флаг с регулярным выражением для валидации
|
||||||
email_flag = Flag(
|
email_flag = Flag(
|
||||||
name="email",
|
name="email",
|
||||||
possible_values=re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")
|
possible_values=re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$"),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -7,14 +7,14 @@ format_flag = Flag(name="format", possible_values=["json", "xml", "csv"])
|
|||||||
|
|
||||||
# Валидация значений
|
# Валидация значений
|
||||||
print(format_flag.validate_input_flag_value("json")) # True
|
print(format_flag.validate_input_flag_value("json")) # True
|
||||||
print(format_flag.validate_input_flag_value("pdf")) # False
|
print(format_flag.validate_input_flag_value("pdf")) # False
|
||||||
|
|
||||||
# Флаг без значения
|
# Флаг без значения
|
||||||
help_flag = Flag(name="help", possible_values=PossibleValues.NEITHER)
|
help_flag = Flag(name="help", possible_values=PossibleValues.NEITHER)
|
||||||
print(help_flag.validate_input_flag_value(None)) # True
|
print(help_flag.validate_input_flag_value(None)) # True
|
||||||
print(help_flag.validate_input_flag_value("value")) # False
|
print(help_flag.validate_input_flag_value("value")) # False
|
||||||
|
|
||||||
# Флаг с регулярным выражением
|
# Флаг с регулярным выражением
|
||||||
port_flag = Flag(name="port", possible_values=re.compile(r"^\d{1,5}$"))
|
port_flag = Flag(name="port", possible_values=re.compile(r"^\d{1,5}$"))
|
||||||
print(port_flag.validate_input_flag_value("8080")) # True
|
print(port_flag.validate_input_flag_value("8080")) # True
|
||||||
print(port_flag.validate_input_flag_value("abc")) # False
|
print(port_flag.validate_input_flag_value("abc")) # False
|
||||||
|
|||||||
@@ -7,5 +7,5 @@ triple_flag = Flag(name="debug", prefix="---")
|
|||||||
|
|
||||||
# Получение строкового представления
|
# Получение строкового представления
|
||||||
print(verbose_flag.string_entity) # --verbose
|
print(verbose_flag.string_entity) # --verbose
|
||||||
print(short_flag.string_entity) # -v
|
print(short_flag.string_entity) # -v
|
||||||
print(triple_flag.string_entity) # ---debug
|
print(triple_flag.string_entity) # ---debug
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ help_flag = Flag(name="help")
|
|||||||
version_flag = Flag(name="V", prefix="-")
|
version_flag = Flag(name="V", prefix="-")
|
||||||
|
|
||||||
# Использование str() или print()
|
# Использование str() или print()
|
||||||
print(str(help_flag)) # --help
|
print(str(help_flag)) # --help
|
||||||
print(version_flag) # -V
|
print(version_flag) # -V
|
||||||
|
|
||||||
# Форматирование строк
|
# Форматирование строк
|
||||||
message = f"Use {help_flag} to see help"
|
message = f"Use {help_flag} to see help"
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ short_flag = Flag(name="v", prefix="-")
|
|||||||
|
|
||||||
# Отладочное представление
|
# Отладочное представление
|
||||||
print(repr(verbose_flag)) # Flag<prefix=--, name=verbose>
|
print(repr(verbose_flag)) # Flag<prefix=--, name=verbose>
|
||||||
print(repr(short_flag)) # Flag<prefix=-, name=v>
|
print(repr(short_flag)) # Flag<prefix=-, name=v>
|
||||||
|
|
||||||
# В интерактивной консоли или отладчике
|
# В интерактивной консоли или отладчике
|
||||||
# >>> verbose_flag
|
# >>> verbose_flag
|
||||||
|
|||||||
@@ -4,14 +4,14 @@ from argenta import Command
|
|||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
# Создание коллекции с флагами
|
# Создание коллекции с флагами
|
||||||
flags = Flags([
|
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}$"))
|
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(
|
cmd = Command("start", description="Start the server", flags=flags)
|
||||||
"start",
|
|
||||||
description="Start the server",
|
|
||||||
flags=flags
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -2,16 +2,14 @@ from argenta.command import Flag, Flags
|
|||||||
from argenta.command.flag.defaults import PredefinedFlags
|
from argenta.command.flag.defaults import PredefinedFlags
|
||||||
|
|
||||||
# Начальная коллекция
|
# Начальная коллекция
|
||||||
flags = Flags([
|
flags = Flags([PredefinedFlags.HOST])
|
||||||
PredefinedFlags.HOST
|
|
||||||
])
|
|
||||||
|
|
||||||
# Дополнительные флаги
|
# Дополнительные флаги
|
||||||
additional_flags = [
|
additional_flags = [
|
||||||
PredefinedFlags.PORT,
|
PredefinedFlags.PORT,
|
||||||
Flag("database"),
|
Flag("database"),
|
||||||
Flag("ssl"),
|
Flag("ssl"),
|
||||||
Flag("verbose")
|
Flag("verbose"),
|
||||||
]
|
]
|
||||||
|
|
||||||
# Добавление списка флагов
|
# Добавление списка флагов
|
||||||
|
|||||||
@@ -1,11 +1,7 @@
|
|||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
from argenta.command.flag.defaults import PredefinedFlags
|
from argenta.command.flag.defaults import PredefinedFlags
|
||||||
|
|
||||||
flags = Flags([
|
flags = Flags([PredefinedFlags.HOST, PredefinedFlags.PORT, Flag("verbose")])
|
||||||
PredefinedFlags.HOST,
|
|
||||||
PredefinedFlags.PORT,
|
|
||||||
Flag("verbose")
|
|
||||||
])
|
|
||||||
|
|
||||||
# Получение флага по имени
|
# Получение флага по имени
|
||||||
host_flag = flags.get_flag_by_name("host")
|
host_flag = flags.get_flag_by_name("host")
|
||||||
|
|||||||
@@ -1,11 +1,7 @@
|
|||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
from argenta.command.flag.defaults import PredefinedFlags
|
from argenta.command.flag.defaults import PredefinedFlags
|
||||||
|
|
||||||
flags = Flags([
|
flags = Flags([PredefinedFlags.HOST, PredefinedFlags.PORT, Flag("verbose")])
|
||||||
PredefinedFlags.HOST,
|
|
||||||
PredefinedFlags.PORT,
|
|
||||||
Flag("verbose")
|
|
||||||
])
|
|
||||||
|
|
||||||
# Итерация по всем флагам
|
# Итерация по всем флагам
|
||||||
for flag in flags:
|
for flag in flags:
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
from argenta.command import Flag, Flags
|
from argenta.command import Flag, Flags
|
||||||
|
|
||||||
flags = Flags([
|
flags = Flags([Flag("first"), Flag("second"), Flag("third")])
|
||||||
Flag("first"),
|
|
||||||
Flag("second"),
|
|
||||||
Flag("third")
|
|
||||||
])
|
|
||||||
|
|
||||||
print(flags[0].name)
|
print(flags[0].name)
|
||||||
# first
|
# first
|
||||||
|
|||||||
@@ -2,16 +2,10 @@ from argenta.command.flag import InputFlag, ValidationStatus
|
|||||||
|
|
||||||
# Создание InputFlag с полным набором параметров
|
# Создание InputFlag с полным набором параметров
|
||||||
output_flag = InputFlag(
|
output_flag = InputFlag(
|
||||||
name="output",
|
name="output", prefix="--", input_value="result.txt", status=ValidationStatus.VALID
|
||||||
prefix="--",
|
|
||||||
input_value="result.txt",
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Флаг без значения
|
# Флаг без значения
|
||||||
help_flag = InputFlag(
|
help_flag = InputFlag(
|
||||||
name="help",
|
name="help", prefix="-", input_value=None, status=ValidationStatus.VALID
|
||||||
prefix="-",
|
|
||||||
input_value=None,
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
from argenta.command.flag import InputFlag, ValidationStatus
|
from argenta.command.flag import InputFlag, ValidationStatus
|
||||||
|
|
||||||
flag = InputFlag(
|
flag = InputFlag(
|
||||||
name="verbose",
|
name="verbose", prefix="-", input_value=None, status=ValidationStatus.VALID
|
||||||
prefix="-",
|
|
||||||
input_value=None,
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Получение строкового представления флага
|
# Получение строкового представления флага
|
||||||
|
|||||||
@@ -1,17 +1,11 @@
|
|||||||
from argenta.command.flag import InputFlag, ValidationStatus
|
from argenta.command.flag import InputFlag, ValidationStatus
|
||||||
|
|
||||||
flag_with_value = InputFlag(
|
flag_with_value = InputFlag(
|
||||||
name="output",
|
name="output", prefix="--", input_value="result.txt", status=ValidationStatus.VALID
|
||||||
prefix="--",
|
|
||||||
input_value="result.txt",
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
flag_without_value = InputFlag(
|
flag_without_value = InputFlag(
|
||||||
name="help",
|
name="help", prefix="-", input_value=None, status=ValidationStatus.VALID
|
||||||
prefix="-",
|
|
||||||
input_value=None,
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Строковое представление включает значение
|
# Строковое представление включает значение
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ flag = InputFlag(
|
|||||||
name="config",
|
name="config",
|
||||||
prefix="--",
|
prefix="--",
|
||||||
input_value="settings.json",
|
input_value="settings.json",
|
||||||
status=ValidationStatus.VALID
|
status=ValidationStatus.VALID,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Отладочное представление объекта
|
# Отладочное представление объекта
|
||||||
|
|||||||
@@ -1,17 +1,11 @@
|
|||||||
from argenta.command.flag import InputFlag, ValidationStatus
|
from argenta.command.flag import InputFlag, ValidationStatus
|
||||||
|
|
||||||
flag1 = InputFlag(
|
flag1 = InputFlag(
|
||||||
name="debug",
|
name="debug", prefix="--", input_value=None, status=ValidationStatus.VALID
|
||||||
prefix="--",
|
|
||||||
input_value=None,
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
flag2 = InputFlag(
|
flag2 = InputFlag(
|
||||||
name="debug",
|
name="debug", prefix="-", input_value="true", status=ValidationStatus.INVALID
|
||||||
prefix="-",
|
|
||||||
input_value="true",
|
|
||||||
status=ValidationStatus.INVALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Сравнение по имени (префикс и значение не учитываются)
|
# Сравнение по имени (префикс и значение не учитываются)
|
||||||
|
|||||||
@@ -3,14 +3,14 @@ from argenta.command import Flag, Flags
|
|||||||
|
|
||||||
router = Router(title="Example")
|
router = Router(title="Example")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"example",
|
@router.command(
|
||||||
description="Example command with flags",
|
Command(
|
||||||
flags=Flags([
|
"example",
|
||||||
Flag("name"),
|
description="Example command with flags",
|
||||||
Flag("age")
|
flags=Flags([Flag("name"), Flag("age")]),
|
||||||
])
|
)
|
||||||
))
|
)
|
||||||
def example_handler(response: Response):
|
def example_handler(response: Response):
|
||||||
# response.input_flags содержит коллекцию InputFlags
|
# response.input_flags содержит коллекцию InputFlags
|
||||||
input_flags = response.input_flags
|
input_flags = response.input_flags
|
||||||
@@ -20,4 +20,3 @@ def example_handler(response: Response):
|
|||||||
print(f"Received {len(input_flags.flags)} flag(s)")
|
print(f"Received {len(input_flags.flags)} flag(s)")
|
||||||
else:
|
else:
|
||||||
print("No flags provided")
|
print("No flags provided")
|
||||||
|
|
||||||
|
|||||||
@@ -4,15 +4,20 @@ from argenta.command.flag import ValidationStatus
|
|||||||
|
|
||||||
router = Router(title="Comprehensive Example")
|
router = Router(title="Comprehensive Example")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"validate",
|
@router.command(
|
||||||
description="Validate all flags",
|
Command(
|
||||||
flags=Flags([
|
"validate",
|
||||||
Flag("format", possible_values=["json", "xml"]),
|
description="Validate all flags",
|
||||||
Flag("output"),
|
flags=Flags(
|
||||||
Flag("force")
|
[
|
||||||
])
|
Flag("format", possible_values=["json", "xml"]),
|
||||||
))
|
Flag("output"),
|
||||||
|
Flag("force"),
|
||||||
|
]
|
||||||
|
),
|
||||||
|
)
|
||||||
|
)
|
||||||
def validate_handler(response: Response):
|
def validate_handler(response: Response):
|
||||||
input_flags = response.input_flags
|
input_flags = response.input_flags
|
||||||
|
|
||||||
@@ -45,4 +50,3 @@ def validate_handler(response: Response):
|
|||||||
print("\nProcessing valid flags:")
|
print("\nProcessing valid flags:")
|
||||||
for flag in valid_flags:
|
for flag in valid_flags:
|
||||||
print(f" Processing {flag.name} = {flag.input_value}")
|
print(f" Processing {flag.name} = {flag.input_value}")
|
||||||
|
|
||||||
|
|||||||
@@ -3,15 +3,14 @@ from argenta.command import Flag, Flags
|
|||||||
|
|
||||||
router = Router(title="Get Flag Example")
|
router = Router(title="Get Flag Example")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"config",
|
@router.command(
|
||||||
description="Configure settings",
|
Command(
|
||||||
flags=Flags([
|
"config",
|
||||||
Flag("host"),
|
description="Configure settings",
|
||||||
Flag("port"),
|
flags=Flags([Flag("host"), Flag("port"), Flag("debug")]),
|
||||||
Flag("debug")
|
)
|
||||||
])
|
)
|
||||||
))
|
|
||||||
def config_handler(response: Response):
|
def config_handler(response: Response):
|
||||||
input_flags = response.input_flags
|
input_flags = response.input_flags
|
||||||
|
|
||||||
@@ -33,4 +32,3 @@ def config_handler(response: Response):
|
|||||||
missing_flag = input_flags.get_flag_by_name("nonexistent")
|
missing_flag = input_flags.get_flag_by_name("nonexistent")
|
||||||
if missing_flag is None:
|
if missing_flag is None:
|
||||||
print("Flag 'nonexistent' not found")
|
print("Flag 'nonexistent' not found")
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from argenta.command.flag import InputFlag, InputFlags, ValidationStatus
|
|||||||
|
|
||||||
router = Router(title="Add Flag Example")
|
router = Router(title="Add Flag Example")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("test", description="Test command"))
|
@router.command(Command("test", description="Test command"))
|
||||||
def test_handler(response: Response):
|
def test_handler(response: Response):
|
||||||
# Создаём новую коллекцию InputFlags
|
# Создаём новую коллекцию InputFlags
|
||||||
@@ -10,13 +11,9 @@ def test_handler(response: Response):
|
|||||||
|
|
||||||
# Добавляем один флаг
|
# Добавляем один флаг
|
||||||
test_flag = InputFlag(
|
test_flag = InputFlag(
|
||||||
name="test",
|
name="test", prefix="--", input_value="value", status=ValidationStatus.VALID
|
||||||
prefix="--",
|
|
||||||
input_value="value",
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
new_flags.add_flag(test_flag)
|
new_flags.add_flag(test_flag)
|
||||||
|
|
||||||
print(f"Flags count: {len(new_flags.flags)}")
|
print(f"Flags count: {len(new_flags.flags)}")
|
||||||
print(f"First flag: {new_flags.flags[0].name}")
|
print(f"First flag: {new_flags.flags[0].name}")
|
||||||
|
|
||||||
|
|||||||
@@ -5,24 +5,15 @@ flags = InputFlags()
|
|||||||
|
|
||||||
# Создаём несколько флагов
|
# Создаём несколько флагов
|
||||||
flag1 = InputFlag(
|
flag1 = InputFlag(
|
||||||
name="option1",
|
name="option1", prefix="--", input_value="value1", status=ValidationStatus.VALID
|
||||||
prefix="--",
|
|
||||||
input_value="value1",
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
flag2 = InputFlag(
|
flag2 = InputFlag(
|
||||||
name="option2",
|
name="option2", prefix="--", input_value="value2", status=ValidationStatus.VALID
|
||||||
prefix="--",
|
|
||||||
input_value="value2",
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
flag3 = InputFlag(
|
flag3 = InputFlag(
|
||||||
name="option3",
|
name="option3", prefix="---", input_value="value3", status=ValidationStatus.VALID
|
||||||
prefix="---",
|
|
||||||
input_value="value3",
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Добавляем все флаги одним вызовом
|
# Добавляем все флаги одним вызовом
|
||||||
@@ -31,4 +22,3 @@ flags.add_flags([flag1, flag2, flag3])
|
|||||||
print(f"Total flags: {len(flags.flags)}")
|
print(f"Total flags: {len(flags.flags)}")
|
||||||
for flag in flags:
|
for flag in flags:
|
||||||
print(f" - {flag.string_entity}: {flag.input_value}")
|
print(f" - {flag.string_entity}: {flag.input_value}")
|
||||||
|
|
||||||
|
|||||||
@@ -3,15 +3,14 @@ from argenta.command import Flag, Flags
|
|||||||
|
|
||||||
router = Router(title="Iterate Example")
|
router = Router(title="Iterate Example")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"process",
|
@router.command(
|
||||||
description="Process with multiple flags",
|
Command(
|
||||||
flags=Flags([
|
"process",
|
||||||
Flag("file"),
|
description="Process with multiple flags",
|
||||||
Flag("format"),
|
flags=Flags([Flag("file"), Flag("format"), Flag("output")]),
|
||||||
Flag("output")
|
)
|
||||||
])
|
)
|
||||||
))
|
|
||||||
def process_handler(response: Response):
|
def process_handler(response: Response):
|
||||||
input_flags = response.input_flags
|
input_flags = response.input_flags
|
||||||
|
|
||||||
@@ -25,4 +24,3 @@ def process_handler(response: Response):
|
|||||||
print("\nFlags with indices:")
|
print("\nFlags with indices:")
|
||||||
for index, flag in enumerate(input_flags):
|
for index, flag in enumerate(input_flags):
|
||||||
print(f" [{index}] {flag.name}: {flag.input_value}")
|
print(f" [{index}] {flag.name}: {flag.input_value}")
|
||||||
|
|
||||||
|
|||||||
@@ -3,15 +3,14 @@ from argenta.command import Flag, Flags
|
|||||||
|
|
||||||
router = Router(title="Index Access Example")
|
router = Router(title="Index Access Example")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"example",
|
@router.command(
|
||||||
description="Example with indexed access",
|
Command(
|
||||||
flags=Flags([
|
"example",
|
||||||
Flag("first"),
|
description="Example with indexed access",
|
||||||
Flag("second"),
|
flags=Flags([Flag("first"), Flag("second"), Flag("third")]),
|
||||||
Flag("third")
|
)
|
||||||
])
|
)
|
||||||
))
|
|
||||||
def example_handler(response: Response):
|
def example_handler(response: Response):
|
||||||
input_flags = response.input_flags
|
input_flags = response.input_flags
|
||||||
|
|
||||||
@@ -28,4 +27,3 @@ def example_handler(response: Response):
|
|||||||
if len(input_flags.flags) >= 2:
|
if len(input_flags.flags) >= 2:
|
||||||
first_two = input_flags.flags[:2]
|
first_two = input_flags.flags[:2]
|
||||||
print(f"First two flags: {[f.name for f in first_two]}")
|
print(f"First two flags: {[f.name for f in first_two]}")
|
||||||
|
|
||||||
|
|||||||
@@ -3,14 +3,14 @@ from argenta.command import Flag, Flags
|
|||||||
|
|
||||||
router = Router(title="Bool Check Example")
|
router = Router(title="Bool Check Example")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"action",
|
@router.command(
|
||||||
description="Action with optional flags",
|
Command(
|
||||||
flags=Flags([
|
"action",
|
||||||
Flag("option1"),
|
description="Action with optional flags",
|
||||||
Flag("option2")
|
flags=Flags([Flag("option1"), Flag("option2")]),
|
||||||
])
|
)
|
||||||
))
|
)
|
||||||
def action_handler(response: Response):
|
def action_handler(response: Response):
|
||||||
input_flags = response.input_flags
|
input_flags = response.input_flags
|
||||||
|
|
||||||
@@ -25,4 +25,3 @@ def action_handler(response: Response):
|
|||||||
# Альтернативный способ проверки
|
# Альтернативный способ проверки
|
||||||
has_flags = bool(input_flags)
|
has_flags = bool(input_flags)
|
||||||
print(f"\nHas flags: {has_flags}")
|
print(f"\nHas flags: {has_flags}")
|
||||||
|
|
||||||
|
|||||||
@@ -2,29 +2,36 @@ from argenta.command.flag import InputFlag, ValidationStatus
|
|||||||
from argenta.command.flag.flags.models import InputFlags
|
from argenta.command.flag.flags.models import InputFlags
|
||||||
|
|
||||||
# Создаём первую коллекцию
|
# Создаём первую коллекцию
|
||||||
flags1 = InputFlags([
|
flags1 = InputFlags(
|
||||||
InputFlag(name="flag1", input_value="value1", status=ValidationStatus.VALID),
|
[
|
||||||
InputFlag(name="flag2", input_value="value2", status=ValidationStatus.VALID)
|
InputFlag(name="flag1", input_value="value1", status=ValidationStatus.VALID),
|
||||||
])
|
InputFlag(name="flag2", input_value="value2", status=ValidationStatus.VALID),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
# Создаём вторую коллекцию с теми же флагами
|
# Создаём вторую коллекцию с теми же флагами
|
||||||
flags2 = InputFlags([
|
flags2 = InputFlags(
|
||||||
InputFlag(name="flag1", input_value="value1", status=ValidationStatus.VALID),
|
[
|
||||||
InputFlag(name="flag2", input_value="value2", status=ValidationStatus.VALID)
|
InputFlag(name="flag1", input_value="value1", status=ValidationStatus.VALID),
|
||||||
])
|
InputFlag(name="flag2", input_value="value2", status=ValidationStatus.VALID),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
# Создаём третью коллекцию с другими флагами
|
# Создаём третью коллекцию с другими флагами
|
||||||
flags3 = InputFlags([
|
flags3 = InputFlags(
|
||||||
InputFlag(name="flag1", input_value="different", status=ValidationStatus.VALID),
|
[
|
||||||
InputFlag(name="flag2", input_value="value2", status=ValidationStatus.VALID)
|
InputFlag(name="flag1", input_value="different", status=ValidationStatus.VALID),
|
||||||
])
|
InputFlag(name="flag2", input_value="value2", status=ValidationStatus.VALID),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
print(f"flags1 == flags2: {flags1 == flags2}") # True (одинаковые имена)
|
print(f"flags1 == flags2: {flags1 == flags2}") # True (одинаковые имена)
|
||||||
print(f"flags1 == flags3: {flags1 == flags3}") # True (имена одинаковые, значения не учитываются)
|
print(
|
||||||
|
f"flags1 == flags3: {flags1 == flags3}"
|
||||||
|
) # True (имена одинаковые, значения не учитываются)
|
||||||
|
|
||||||
# Разные коллекции
|
# Разные коллекции
|
||||||
flags4 = InputFlags([
|
flags4 = InputFlags(
|
||||||
InputFlag(name="flag3", input_value="value3", status=ValidationStatus.VALID)
|
[InputFlag(name="flag3", input_value="value3", status=ValidationStatus.VALID)]
|
||||||
])
|
)
|
||||||
print(f"flags1 == flags4: {flags1 == flags4}") # False (разные флаги)
|
print(f"flags1 == flags4: {flags1 == flags4}") # False (разные флаги)
|
||||||
|
|
||||||
|
|||||||
@@ -4,15 +4,14 @@ from argenta.command.flag import InputFlag
|
|||||||
|
|
||||||
router = Router(title="Contains Example")
|
router = Router(title="Contains Example")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"check",
|
@router.command(
|
||||||
description="Check flags",
|
Command(
|
||||||
flags=Flags([
|
"check",
|
||||||
Flag("verbose"),
|
description="Check flags",
|
||||||
Flag("debug"),
|
flags=Flags([Flag("verbose"), Flag("debug"), Flag("quiet")]),
|
||||||
Flag("quiet")
|
)
|
||||||
])
|
)
|
||||||
))
|
|
||||||
def check_handler(response: Response):
|
def check_handler(response: Response):
|
||||||
input_flags = response.input_flags
|
input_flags = response.input_flags
|
||||||
|
|
||||||
@@ -28,13 +27,7 @@ def check_handler(response: Response):
|
|||||||
print("Debug flag is present")
|
print("Debug flag is present")
|
||||||
|
|
||||||
# Можно создать флаг для проверки (сравнение идёт по имени)
|
# Можно создать флаг для проверки (сравнение идёт по имени)
|
||||||
test_flag = InputFlag(
|
test_flag = InputFlag(name="verbose", prefix="--", input_value="any", status=None)
|
||||||
name="verbose",
|
|
||||||
prefix="--",
|
|
||||||
input_value="any",
|
|
||||||
status=None
|
|
||||||
)
|
|
||||||
|
|
||||||
if test_flag in input_flags:
|
if test_flag in input_flags:
|
||||||
print("Verbose flag found using 'in' operator")
|
print("Verbose flag found using 'in' operator")
|
||||||
|
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ class ConnectionProvider(Provider):
|
|||||||
yield conn
|
yield conn
|
||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
# 2. Создаем и настраиваем App
|
# 2. Создаем и настраиваем App
|
||||||
app = App()
|
app = App()
|
||||||
# ... здесь можно добавить роутеры ...
|
# ... здесь можно добавить роутеры ...
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ def custom_print_function(text: str) -> None:
|
|||||||
"""Простая пользовательская функция вывода с префиксом."""
|
"""Простая пользовательская функция вывода с префиксом."""
|
||||||
print(f"Префикс: {text}")
|
print(f"Префикс: {text}")
|
||||||
|
|
||||||
|
|
||||||
app = App(
|
app = App(
|
||||||
initial_message="My App",
|
initial_message="My App",
|
||||||
override_system_messages=True,
|
override_system_messages=True,
|
||||||
|
|||||||
@@ -3,25 +3,13 @@ import re
|
|||||||
from argenta.command import Flag, PossibleValues
|
from argenta.command import Flag, PossibleValues
|
||||||
|
|
||||||
# Флаг без значения
|
# Флаг без значения
|
||||||
verbose_flag = Flag(
|
verbose_flag = Flag(name="verbose", possible_values=PossibleValues.NEITHER)
|
||||||
name="verbose",
|
|
||||||
possible_values=PossibleValues.NEITHER
|
|
||||||
)
|
|
||||||
|
|
||||||
# Флаг с любым значением
|
# Флаг с любым значением
|
||||||
output_flag = Flag(
|
output_flag = Flag(name="output", possible_values=PossibleValues.ALL)
|
||||||
name="output",
|
|
||||||
possible_values=PossibleValues.ALL
|
|
||||||
)
|
|
||||||
|
|
||||||
# Флаг со списком допустимых значений
|
# Флаг со списком допустимых значений
|
||||||
format_flag = Flag(
|
format_flag = Flag(name="format", possible_values=["json", "xml", "csv", "yaml"])
|
||||||
name="format",
|
|
||||||
possible_values=["json", "xml", "csv", "yaml"]
|
|
||||||
)
|
|
||||||
|
|
||||||
# Флаг с регулярным выражением
|
# Флаг с регулярным выражением
|
||||||
email_flag = Flag(
|
email_flag = Flag(name="email", possible_values=re.compile(r"^[\w\.-]+@[\w\.-]+\.\w+$"))
|
||||||
name="email",
|
|
||||||
possible_values=re.compile(r"^[\w\.-]+@[\w\.-]+\.\w+$")
|
|
||||||
)
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
from argenta.command.flag.defaults import PredefinedFlags
|
from argenta.command.flag.defaults import PredefinedFlags
|
||||||
|
|
||||||
# Проверка типа possible_values в предопределенных флагах
|
# Проверка типа possible_values в предопределенных флагах
|
||||||
print(PredefinedFlags.HELP.possible_values) # PossibleValues.NEITHER
|
print(PredefinedFlags.HELP.possible_values) # PossibleValues.NEITHER
|
||||||
print(PredefinedFlags.INFO.possible_values) # PossibleValues.NEITHER
|
print(PredefinedFlags.INFO.possible_values) # PossibleValues.NEITHER
|
||||||
print(PredefinedFlags.ALL.possible_values) # PossibleValues.NEITHER
|
print(PredefinedFlags.ALL.possible_values) # PossibleValues.NEITHER
|
||||||
|
|
||||||
# Сетевые флаги используют регулярные выражения, а не PossibleValues
|
# Сетевые флаги используют регулярные выражения, а не PossibleValues
|
||||||
# PredefinedFlags.HOST использует Pattern для валидации IP
|
# PredefinedFlags.HOST использует Pattern для валидации IP
|
||||||
|
|||||||
@@ -6,10 +6,11 @@ from argenta import App, Orchestrator
|
|||||||
app: App = App()
|
app: App = App()
|
||||||
orchestrator: Orchestrator = Orchestrator()
|
orchestrator: Orchestrator = Orchestrator()
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
app.include_router(router)
|
app.include_router(router)
|
||||||
orchestrator.start_polling(app)
|
orchestrator.start_polling(app)
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
main()
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ from argenta import Command, Response, Router
|
|||||||
|
|
||||||
router = Router(title="Quickstart Example")
|
router = Router(title="Quickstart Example")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("hello", description="Say hello"))
|
@router.command(Command("hello", description="Say hello"))
|
||||||
def handler(response: Response):
|
def handler(response: Response):
|
||||||
print("Hello, world!")
|
print("Hello, world!")
|
||||||
|
|
||||||
@@ -9,14 +9,17 @@ from .repository import Priority, Task, TaskRepository
|
|||||||
|
|
||||||
router = Router(title="Task Manager")
|
router = Router(title="Task Manager")
|
||||||
|
|
||||||
|
|
||||||
@router.command(
|
@router.command(
|
||||||
Command(
|
Command(
|
||||||
"add-task",
|
"add-task",
|
||||||
description="Add a new task",
|
description="Add a new task",
|
||||||
flags=Flags([
|
flags=Flags(
|
||||||
Flag("description"),
|
[
|
||||||
Flag("priority", possible_values=["low", "medium", "high"]),
|
Flag("description"),
|
||||||
])
|
Flag("priority", possible_values=["low", "medium", "high"]),
|
||||||
|
]
|
||||||
|
),
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
def add_task(response: Response, repo: FromDishka[TaskRepository]):
|
def add_task(response: Response, repo: FromDishka[TaskRepository]):
|
||||||
@@ -40,6 +43,7 @@ def add_task(response: Response, repo: FromDishka[TaskRepository]):
|
|||||||
repo.add_task(task)
|
repo.add_task(task)
|
||||||
print(f"Added task: '{task.description}' with priority '{task.priority}'")
|
print(f"Added task: '{task.description}' with priority '{task.priority}'")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("list-tasks", description="List all tasks"))
|
@router.command(Command("list-tasks", description="List all tasks"))
|
||||||
def list_tasks(response: Response, repo: FromDishka[TaskRepository]):
|
def list_tasks(response: Response, repo: FromDishka[TaskRepository]):
|
||||||
tasks = repo.get_all_tasks()
|
tasks = repo.get_all_tasks()
|
||||||
|
|||||||
@@ -3,11 +3,13 @@ from typing import Literal
|
|||||||
|
|
||||||
Priority = Literal["low", "medium", "high"]
|
Priority = Literal["low", "medium", "high"]
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Task:
|
class Task:
|
||||||
description: str
|
description: str
|
||||||
priority: Priority = "medium"
|
priority: Priority = "medium"
|
||||||
|
|
||||||
|
|
||||||
class TaskRepository:
|
class TaskRepository:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._tasks: list[Task] = []
|
self._tasks: list[Task] = []
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from argenta.router import Router
|
|||||||
# Для этого роутера перехват stdout будет отключен
|
# Для этого роутера перехват stdout будет отключен
|
||||||
interactive_router = Router(disable_redirect_stdout=True)
|
interactive_router = Router(disable_redirect_stdout=True)
|
||||||
|
|
||||||
|
|
||||||
@interactive_router.command("ask")
|
@interactive_router.command("ask")
|
||||||
def ask_name(response):
|
def ask_name(response):
|
||||||
name = input("Как вас зовут? ")
|
name = input("Как вас зовут? ")
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from argenta.response import ResponseStatus
|
|||||||
|
|
||||||
router = Router(title="Example")
|
router = Router(title="Example")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("greet", description="Greet the user"))
|
@router.command(Command("greet", description="Greet the user"))
|
||||||
def greet_handler(response: Response):
|
def greet_handler(response: Response):
|
||||||
# response автоматически передаётся в обработчик
|
# response автоматически передаётся в обработчик
|
||||||
@@ -13,4 +14,3 @@ def greet_handler(response: Response):
|
|||||||
print("Hello! All flags are valid.")
|
print("Hello! All flags are valid.")
|
||||||
else:
|
else:
|
||||||
print("Warning: Some flags have issues.")
|
print("Warning: Some flags have issues.")
|
||||||
|
|
||||||
|
|||||||
@@ -2,16 +2,20 @@ from argenta import Command, Response, Router
|
|||||||
|
|
||||||
router = Router(title="Data Example")
|
router = Router(title="Data Example")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("set", description="Set data"))
|
@router.command(Command("set", description="Set data"))
|
||||||
def set_handler(response: Response):
|
def set_handler(response: Response):
|
||||||
# Обновляем глобальное хранилище данных
|
# Обновляем глобальное хранилище данных
|
||||||
response.update_data({
|
response.update_data(
|
||||||
"user_name": "John",
|
{
|
||||||
"timestamp": "2024-01-01",
|
"user_name": "John",
|
||||||
"settings": {"theme": "dark", "language": "ru"}
|
"timestamp": "2024-01-01",
|
||||||
})
|
"settings": {"theme": "dark", "language": "ru"},
|
||||||
|
}
|
||||||
|
)
|
||||||
print("Data updated successfully")
|
print("Data updated successfully")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("show", description="Show data"))
|
@router.command(Command("show", description="Show data"))
|
||||||
def show_handler(response: Response):
|
def show_handler(response: Response):
|
||||||
# Получаем данные из глобального хранилища
|
# Получаем данные из глобального хранилища
|
||||||
@@ -19,4 +23,3 @@ def show_handler(response: Response):
|
|||||||
if "user_name" in data:
|
if "user_name" in data:
|
||||||
print(f"User: {data['user_name']}")
|
print(f"User: {data['user_name']}")
|
||||||
print(f"Settings: {data.get('settings', {})}")
|
print(f"Settings: {data.get('settings', {})}")
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ from argenta import Command, Response, Router
|
|||||||
|
|
||||||
router = Router(title="Get Data Example")
|
router = Router(title="Get Data Example")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("info", description="Show all stored data"))
|
@router.command(Command("info", description="Show all stored data"))
|
||||||
def info_handler(response: Response):
|
def info_handler(response: Response):
|
||||||
# Получаем все данные из глобального хранилища
|
# Получаем все данные из глобального хранилища
|
||||||
@@ -13,4 +14,3 @@ def info_handler(response: Response):
|
|||||||
print(f" {key}: {value}")
|
print(f" {key}: {value}")
|
||||||
else:
|
else:
|
||||||
print("No data stored")
|
print("No data stored")
|
||||||
|
|
||||||
|
|||||||
@@ -2,12 +2,14 @@ from argenta import Command, Response, Router
|
|||||||
|
|
||||||
router = Router(title="Clear Data Example")
|
router = Router(title="Clear Data Example")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("clear", description="Clear all stored data"))
|
@router.command(Command("clear", description="Clear all stored data"))
|
||||||
def clear_handler(response: Response):
|
def clear_handler(response: Response):
|
||||||
# Очищаем всё хранилище данных
|
# Очищаем всё хранилище данных
|
||||||
response.clear_data()
|
response.clear_data()
|
||||||
print("All data cleared")
|
print("All data cleared")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("check", description="Check if data exists"))
|
@router.command(Command("check", description="Check if data exists"))
|
||||||
def check_handler(response: Response):
|
def check_handler(response: Response):
|
||||||
data = response.get_data()
|
data = response.get_data()
|
||||||
@@ -15,4 +17,3 @@ def check_handler(response: Response):
|
|||||||
print(f"Storage contains {len(data)} item(s)")
|
print(f"Storage contains {len(data)} item(s)")
|
||||||
else:
|
else:
|
||||||
print("Storage is empty")
|
print("Storage is empty")
|
||||||
|
|
||||||
|
|||||||
@@ -2,15 +2,19 @@ from argenta import Command, Response, Router
|
|||||||
|
|
||||||
router = Router(title="Delete Data Example")
|
router = Router(title="Delete Data Example")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("store", description="Store data"))
|
@router.command(Command("store", description="Store data"))
|
||||||
def store_handler(response: Response):
|
def store_handler(response: Response):
|
||||||
response.update_data({
|
response.update_data(
|
||||||
"temp_key": "temporary value",
|
{
|
||||||
"important_key": "important value",
|
"temp_key": "temporary value",
|
||||||
"another_key": "another value"
|
"important_key": "important value",
|
||||||
})
|
"another_key": "another value",
|
||||||
|
}
|
||||||
|
)
|
||||||
print("Data stored")
|
print("Data stored")
|
||||||
|
|
||||||
|
|
||||||
@router.command(Command("remove", description="Remove specific key"))
|
@router.command(Command("remove", description="Remove specific key"))
|
||||||
def remove_handler(response: Response):
|
def remove_handler(response: Response):
|
||||||
# Удаляем конкретный ключ из хранилища
|
# Удаляем конкретный ключ из хранилища
|
||||||
@@ -23,4 +27,3 @@ def remove_handler(response: Response):
|
|||||||
print(f"Remaining keys: {list(remaining.keys())}")
|
print(f"Remaining keys: {list(remaining.keys())}")
|
||||||
except KeyError:
|
except KeyError:
|
||||||
print("Key not found")
|
print("Key not found")
|
||||||
|
|
||||||
|
|||||||
@@ -4,14 +4,14 @@ from argenta.response import ResponseStatus
|
|||||||
|
|
||||||
router = Router(title="Flags Example")
|
router = Router(title="Flags Example")
|
||||||
|
|
||||||
@router.command(Command(
|
|
||||||
"process",
|
@router.command(
|
||||||
description="Process with flags",
|
Command(
|
||||||
flags=Flags([
|
"process",
|
||||||
Flag("format", possible_values=["json", "xml"]),
|
description="Process with flags",
|
||||||
Flag("verbose")
|
flags=Flags([Flag("format", possible_values=["json", "xml"]), Flag("verbose")]),
|
||||||
])
|
)
|
||||||
))
|
)
|
||||||
def process_handler(response: Response):
|
def process_handler(response: Response):
|
||||||
# Проверяем статус валидации флагов
|
# Проверяем статус валидации флагов
|
||||||
print(f"Status: {response.status.value}")
|
print(f"Status: {response.status.value}")
|
||||||
@@ -35,4 +35,3 @@ def process_handler(response: Response):
|
|||||||
for flag in response.input_flags:
|
for flag in response.input_flags:
|
||||||
if flag.status and flag.status.name == "INVALID":
|
if flag.status and flag.status.name == "INVALID":
|
||||||
print(f" Invalid flag: {flag.string_entity} = {flag.input_value}")
|
print(f" Invalid flag: {flag.string_entity} = {flag.input_value}")
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from argenta.router import Router
|
|||||||
|
|
||||||
user_router = Router(title="User Management")
|
user_router = Router(title="User Management")
|
||||||
|
|
||||||
|
|
||||||
@user_router.command(Command("add-user", description="Adds a new user"))
|
@user_router.command(Command("add-user", description="Adds a new user"))
|
||||||
def add_user_handler(response):
|
def add_user_handler(response):
|
||||||
# Логика добавления пользователя
|
# Логика добавления пользователя
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
import re
|
import re
|
||||||
|
|
||||||
from argenta.command.flag import (Flag, InputFlag, PossibleValues,
|
from argenta.command.flag import Flag, InputFlag, PossibleValues, ValidationStatus
|
||||||
ValidationStatus)
|
|
||||||
|
|
||||||
# Создаём различные типы флагов
|
# Создаём различные типы флагов
|
||||||
verbose_flag = Flag("verbose", possible_values=PossibleValues.NEITHER)
|
verbose_flag = Flag("verbose", possible_values=PossibleValues.NEITHER)
|
||||||
output_flag = Flag("output", possible_values=PossibleValues.ALL)
|
output_flag = Flag("output", possible_values=PossibleValues.ALL)
|
||||||
level_flag = Flag("level", possible_values=["1", "2", "3"])
|
level_flag = Flag("level", possible_values=["1", "2", "3"])
|
||||||
pattern_flag = Flag("pattern", possible_values=re.compile(r'^[a-zA-Z]+$'))
|
pattern_flag = Flag("pattern", possible_values=re.compile(r"^[a-zA-Z]+$"))
|
||||||
|
|
||||||
# Создаём входные флаги с различными статусами
|
# Создаём входные флаги с различными статусами
|
||||||
input_flags = [
|
input_flags = [
|
||||||
@@ -16,12 +15,10 @@ input_flags = [
|
|||||||
InputFlag("output", input_value="result.txt", status=ValidationStatus.VALID),
|
InputFlag("output", input_value="result.txt", status=ValidationStatus.VALID),
|
||||||
InputFlag("level", input_value="2", status=ValidationStatus.VALID),
|
InputFlag("level", input_value="2", status=ValidationStatus.VALID),
|
||||||
InputFlag("pattern", input_value="onlyletters", status=ValidationStatus.VALID),
|
InputFlag("pattern", input_value="onlyletters", status=ValidationStatus.VALID),
|
||||||
|
|
||||||
# Невалидные флаги
|
# Невалидные флаги
|
||||||
InputFlag("verbose", input_value="true", status=ValidationStatus.INVALID),
|
InputFlag("verbose", input_value="true", status=ValidationStatus.INVALID),
|
||||||
InputFlag("level", input_value="4", status=ValidationStatus.INVALID),
|
InputFlag("level", input_value="4", status=ValidationStatus.INVALID),
|
||||||
InputFlag("pattern", input_value="123", status=ValidationStatus.INVALID),
|
InputFlag("pattern", input_value="123", status=ValidationStatus.INVALID),
|
||||||
|
|
||||||
# Неопределённые флаги
|
# Неопределённые флаги
|
||||||
InputFlag("unknown", input_value="value", status=ValidationStatus.UNDEFINED),
|
InputFlag("unknown", input_value="value", status=ValidationStatus.UNDEFINED),
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -2,21 +2,15 @@ from argenta import InputFlag, ValidationStatus
|
|||||||
|
|
||||||
# Создание входных флагов с различными статусами
|
# Создание входных флагов с различными статусами
|
||||||
valid_flag = InputFlag(
|
valid_flag = InputFlag(
|
||||||
"output",
|
"output", input_value="/path/to/file.txt", status=ValidationStatus.VALID
|
||||||
input_value="/path/to/file.txt",
|
|
||||||
status=ValidationStatus.VALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
invalid_flag = InputFlag(
|
invalid_flag = InputFlag(
|
||||||
"count",
|
"count", input_value="not-a-number", status=ValidationStatus.INVALID
|
||||||
input_value="not-a-number",
|
|
||||||
status=ValidationStatus.INVALID
|
|
||||||
)
|
)
|
||||||
|
|
||||||
undefined_flag = InputFlag(
|
undefined_flag = InputFlag(
|
||||||
"experimental",
|
"experimental", input_value="test", status=ValidationStatus.UNDEFINED
|
||||||
input_value="test",
|
|
||||||
status=ValidationStatus.UNDEFINED
|
|
||||||
)
|
)
|
||||||
|
|
||||||
flags = [valid_flag, invalid_flag, undefined_flag]
|
flags = [valid_flag, invalid_flag, undefined_flag]
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
from argenta.command.flag import (Flag, InputFlag, PossibleValues,
|
from argenta.command.flag import Flag, InputFlag, PossibleValues, ValidationStatus
|
||||||
ValidationStatus)
|
|
||||||
|
|
||||||
# Создание флага без значения
|
# Создание флага без значения
|
||||||
help_flag = Flag("help", possible_values=PossibleValues.NEITHER)
|
help_flag = Flag("help", possible_values=PossibleValues.NEITHER)
|
||||||
|
|||||||
@@ -19,14 +19,17 @@ def process_input_flag(input_flag: InputFlag) -> None:
|
|||||||
# Пытаемся провести валидацию или пропускаем
|
# Пытаемся провести валидацию или пропускаем
|
||||||
attempt_revalidation(input_flag)
|
attempt_revalidation(input_flag)
|
||||||
|
|
||||||
|
|
||||||
def execute_flag_logic(flag: InputFlag) -> None:
|
def execute_flag_logic(flag: InputFlag) -> None:
|
||||||
"""Выполняет логику для валидного флага"""
|
"""Выполняет логику для валидного флага"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def log_validation_error(flag: InputFlag) -> None:
|
def log_validation_error(flag: InputFlag) -> None:
|
||||||
"""Записывает ошибку валидации в лог"""
|
"""Записывает ошибку валидации в лог"""
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def attempt_revalidation(flag: InputFlag) -> None:
|
def attempt_revalidation(flag: InputFlag) -> None:
|
||||||
"""Пытается повторно провести валидацию"""
|
"""Пытается повторно провести валидацию"""
|
||||||
pass
|
pass
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
from argenta import InputFlag, ValidationStatus
|
from argenta import InputFlag, ValidationStatus
|
||||||
|
|
||||||
# Создание входного флага без определения статуса
|
# Создание входного флага без определения статуса
|
||||||
undefined_input = InputFlag("unknown-flag", input_value="some-value", status=ValidationStatus.UNDEFINED)
|
undefined_input = InputFlag(
|
||||||
|
"unknown-flag", input_value="some-value", status=ValidationStatus.UNDEFINED
|
||||||
|
)
|
||||||
|
|
||||||
print(f"Флаг: {undefined_input.string_entity}")
|
print(f"Флаг: {undefined_input.string_entity}")
|
||||||
print(f"Значение: {undefined_input.input_value}")
|
print(f"Значение: {undefined_input.input_value}")
|
||||||
print(f"Статус: {undefined_input.status.value}") # Выведет: UNDEFINED
|
print(f"Статус: {undefined_input.status.value}") # Выведет: UNDEFINED
|
||||||
|
|
||||||
# Или флаг, для которого валидация ещё не проводилась
|
# Или флаг, для которого валидация ещё не проводилась
|
||||||
pending_input = InputFlag("pending", input_value=None, status=ValidationStatus.UNDEFINED)
|
pending_input = InputFlag(
|
||||||
|
"pending", input_value=None, status=ValidationStatus.UNDEFINED
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
from argenta.command.flag import Flag, InputFlag, ValidationStatus
|
from argenta.command.flag import Flag, InputFlag, ValidationStatus
|
||||||
|
|
||||||
# Создание флага, который принимает только определённые значения
|
# Создание флага, который принимает только определённые значения
|
||||||
log_level_flag = Flag("log-level", possible_values=["debug", "info", "warning", "error"])
|
log_level_flag = Flag(
|
||||||
|
"log-level", possible_values=["debug", "info", "warning", "error"]
|
||||||
|
)
|
||||||
|
|
||||||
# Создание корректного входного флага
|
# Создание корректного входного флага
|
||||||
valid_input = InputFlag("log-level", input_value="debug", status=ValidationStatus.VALID)
|
valid_input = InputFlag("log-level", input_value="debug", status=ValidationStatus.VALID)
|
||||||
|
|||||||
Reference in New Issue
Block a user