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