From 9c58c1015226038a0420b8f64b6c1ef5c43bcc56 Mon Sep 17 00:00:00 2001 From: kolo Date: Sun, 2 Nov 2025 01:04:31 +0300 Subject: [PATCH] docs --- docs/code_snippets/argparser/snippet.py | 4 +- docs/code_snippets/argspace/snippet.py | 26 ++++-------- docs/code_snippets/argspace/snippet2.py | 4 +- docs/code_snippets/argspace/snippet3.py | 12 +++--- docs/code_snippets/autocompleter/snippet.py | 2 +- docs/code_snippets/command/snippet.py | 27 +++++------- docs/code_snippets/command/snippet2.py | 21 +++++----- docs/code_snippets/command/snippet3.py | 31 ++++++++------ docs/code_snippets/command/snippet4.py | 2 +- .../dependency_injection/snippet.py | 6 +-- .../dependency_injection/snippet2.py | 2 +- .../dependency_injection/snippet4.py | 6 +-- docs/code_snippets/dividing_lines/snippet.py | 2 +- docs/code_snippets/error_handling/snippet.py | 1 + docs/code_snippets/error_handling/snippet2.py | 1 + docs/code_snippets/error_handling/snippet3.py | 1 + docs/code_snippets/error_handling/snippet4.py | 1 + docs/code_snippets/error_handling/snippet5.py | 1 + docs/code_snippets/error_handling/snippet6.py | 1 + docs/code_snippets/flag/predefined_flags.py | 42 ++++++++++--------- docs/code_snippets/flag/snippet.py | 7 +--- docs/code_snippets/flag/snippet2.py | 10 ++--- docs/code_snippets/flag/snippet3.py | 4 +- docs/code_snippets/flag/snippet4.py | 4 +- docs/code_snippets/flag/snippet5.py | 2 +- docs/code_snippets/flags/snippet.py | 18 ++++---- docs/code_snippets/flags/snippet2.py | 2 +- docs/code_snippets/flags/snippet3.py | 8 ++-- docs/code_snippets/flags/snippet4.py | 8 +--- docs/code_snippets/flags/snippet5.py | 8 +--- docs/code_snippets/flags/snippet6.py | 8 +--- docs/code_snippets/input_flag/snippet1.py | 10 +---- docs/code_snippets/input_flag/snippet2.py | 5 +-- docs/code_snippets/input_flag/snippet3.py | 10 +---- docs/code_snippets/input_flag/snippet4.py | 2 +- docs/code_snippets/input_flag/snippet5.py | 10 +---- docs/code_snippets/input_flags/snippet1.py | 19 ++++----- docs/code_snippets/input_flags/snippet10.py | 34 ++++++++------- docs/code_snippets/input_flags/snippet2.py | 28 ++++++------- docs/code_snippets/input_flags/snippet3.py | 11 ++--- docs/code_snippets/input_flags/snippet4.py | 16 ++----- docs/code_snippets/input_flags/snippet5.py | 22 +++++----- docs/code_snippets/input_flags/snippet6.py | 24 +++++------ docs/code_snippets/input_flags/snippet7.py | 21 +++++----- docs/code_snippets/input_flags/snippet8.py | 41 ++++++++++-------- docs/code_snippets/input_flags/snippet9.py | 35 +++++++--------- docs/code_snippets/orchestrator/snippet.py | 3 +- .../overriding_formatting/sample.py | 1 + docs/code_snippets/possible_values/all.py | 2 +- .../code_snippets/possible_values/combined.py | 20 ++------- .../possible_values/predefined.py | 6 +-- docs/code_snippets/quickstart/main.py | 5 ++- docs/code_snippets/quickstart/routers.py | 2 +- .../quickstart/task_manager/handlers.py | 12 ++++-- .../quickstart/task_manager/repository.py | 2 + docs/code_snippets/redirect_stdout/sample.py | 3 +- docs/code_snippets/redirect_stdout/sample2.py | 2 +- docs/code_snippets/response/snippet1.py | 4 +- docs/code_snippets/response/snippet2.py | 15 ++++--- docs/code_snippets/response/snippet3.py | 4 +- docs/code_snippets/response/snippet4.py | 3 +- docs/code_snippets/response/snippet5.py | 17 ++++---- docs/code_snippets/response/snippet6.py | 25 ++++++----- docs/code_snippets/router/snippet.py | 3 +- .../validation_status/comprehensive.py | 7 +--- .../validation_status/input_flag.py | 12 ++---- .../validation_status/invalid.py | 3 +- .../validation_status/processing.py | 9 ++-- .../validation_status/undefined.py | 8 +++- docs/code_snippets/validation_status/valid.py | 4 +- 70 files changed, 341 insertions(+), 391 deletions(-) diff --git a/docs/code_snippets/argparser/snippet.py b/docs/code_snippets/argparser/snippet.py index e9f0c33..b86b95f 100644 --- a/docs/code_snippets/argparser/snippet.py +++ b/docs/code_snippets/argparser/snippet.py @@ -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()) \ No newline at end of file + orchestrator.start_polling(App()) diff --git a/docs/code_snippets/argspace/snippet.py b/docs/code_snippets/argspace/snippet.py index c4266d5..c40553b 100644 --- a/docs/code_snippets/argspace/snippet.py +++ b/docs/code_snippets/argspace/snippet.py @@ -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() - \ No newline at end of file diff --git a/docs/code_snippets/argspace/snippet2.py b/docs/code_snippets/argspace/snippet2.py index 3a7f4bb..14ae759 100644 --- a/docs/code_snippets/argspace/snippet2.py +++ b/docs/code_snippets/argspace/snippet2.py @@ -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) - \ No newline at end of file diff --git a/docs/code_snippets/argspace/snippet3.py b/docs/code_snippets/argspace/snippet3.py index 1264345..3159a42 100644 --- a/docs/code_snippets/argspace/snippet3.py +++ b/docs/code_snippets/argspace/snippet3.py @@ -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))}") \ No newline at end of file + print(f"Value arguments: {len(argspace.get_by_type(ValueArgument))}") diff --git a/docs/code_snippets/autocompleter/snippet.py b/docs/code_snippets/autocompleter/snippet.py index c9dc4da..fcb194c 100644 --- a/docs/code_snippets/autocompleter/snippet.py +++ b/docs/code_snippets/autocompleter/snippet.py @@ -7,4 +7,4 @@ my_autocompleter = AutoCompleter(history_filename="argenta_history.txt") # Передача настроенного автокомплитера в приложение app = App(autocompleter=my_autocompleter) -# ... остальная логика приложения \ No newline at end of file +# ... остальная логика приложения diff --git a/docs/code_snippets/command/snippet.py b/docs/code_snippets/command/snippet.py index 9761be9..ab082ca 100644 --- a/docs/code_snippets/command/snippet.py +++ b/docs/code_snippets/command/snippet.py @@ -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"] -) \ No newline at end of file + flags=Flags( + [ + Flag("env", help="Environment name", possible_values=["dev", "prod"]), + Flag("force", help="Force deployment"), + ] + ), + aliases=["dep"], +) diff --git a/docs/code_snippets/command/snippet2.py b/docs/code_snippets/command/snippet2.py index d85d824..1a32810 100644 --- a/docs/code_snippets/command/snippet2.py +++ b/docs/code_snippets/command/snippet2.py @@ -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...") \ No newline at end of file + print("Deleting user...") diff --git a/docs/code_snippets/command/snippet3.py b/docs/code_snippets/command/snippet3.py index d75c6b5..e4e21bd 100644 --- a/docs/code_snippets/command/snippet3.py +++ b/docs/code_snippets/command/snippet3.py @@ -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") \ No newline at end of file + print("Debug mode: ON") diff --git a/docs/code_snippets/command/snippet4.py b/docs/code_snippets/command/snippet4.py index d612c28..aba2501 100644 --- a/docs/code_snippets/command/snippet4.py +++ b/docs/code_snippets/command/snippet4.py @@ -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 \ No newline at end of file +print(len(cmd2.input_flags)) # 2 diff --git a/docs/code_snippets/dependency_injection/snippet.py b/docs/code_snippets/dependency_injection/snippet.py index dd9c7cb..b2d310b 100644 --- a/docs/code_snippets/dependency_injection/snippet.py +++ b/docs/code_snippets/dependency_injection/snippet.py @@ -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('...') - \ No newline at end of file + connection.execute("...") diff --git a/docs/code_snippets/dependency_injection/snippet2.py b/docs/code_snippets/dependency_injection/snippet2.py index b4e01ca..2bb4584 100644 --- a/docs/code_snippets/dependency_injection/snippet2.py +++ b/docs/code_snippets/dependency_injection/snippet2.py @@ -10,4 +10,4 @@ class ConnectionProvider(Provider): def new_connection(self) -> Iterable[Connection]: conn = sqlite3.connect(":memory:") yield conn - conn.close() \ No newline at end of file + conn.close() diff --git a/docs/code_snippets/dependency_injection/snippet4.py b/docs/code_snippets/dependency_injection/snippet4.py index ddd63cd..5ce3a03 100644 --- a/docs/code_snippets/dependency_injection/snippet4.py +++ b/docs/code_snippets/dependency_injection/snippet4.py @@ -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')) - \ No newline at end of file + print(argspace.get_by_name("type")) diff --git a/docs/code_snippets/dividing_lines/snippet.py b/docs/code_snippets/dividing_lines/snippet.py index 9b8259c..92d6508 100644 --- a/docs/code_snippets/dividing_lines/snippet.py +++ b/docs/code_snippets/dividing_lines/snippet.py @@ -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) \ No newline at end of file +app_with_dynamic_line = App(dividing_line=dynamic_line) diff --git a/docs/code_snippets/error_handling/snippet.py b/docs/code_snippets/error_handling/snippet.py index a274bb1..63988e2 100644 --- a/docs/code_snippets/error_handling/snippet.py +++ b/docs/code_snippets/error_handling/snippet.py @@ -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) diff --git a/docs/code_snippets/error_handling/snippet2.py b/docs/code_snippets/error_handling/snippet2.py index f5c9dee..08a7124 100644 --- a/docs/code_snippets/error_handling/snippet2.py +++ b/docs/code_snippets/error_handling/snippet2.py @@ -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) diff --git a/docs/code_snippets/error_handling/snippet3.py b/docs/code_snippets/error_handling/snippet3.py index 25882d2..b3a0f15 100644 --- a/docs/code_snippets/error_handling/snippet3.py +++ b/docs/code_snippets/error_handling/snippet3.py @@ -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) diff --git a/docs/code_snippets/error_handling/snippet4.py b/docs/code_snippets/error_handling/snippet4.py index 03cf6ea..972eff9 100644 --- a/docs/code_snippets/error_handling/snippet4.py +++ b/docs/code_snippets/error_handling/snippet4.py @@ -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) diff --git a/docs/code_snippets/error_handling/snippet5.py b/docs/code_snippets/error_handling/snippet5.py index b1bb033..575ffab 100644 --- a/docs/code_snippets/error_handling/snippet5.py +++ b/docs/code_snippets/error_handling/snippet5.py @@ -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) diff --git a/docs/code_snippets/error_handling/snippet6.py b/docs/code_snippets/error_handling/snippet6.py index 4f336f3..0dcda57 100644 --- a/docs/code_snippets/error_handling/snippet6.py +++ b/docs/code_snippets/error_handling/snippet6.py @@ -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) diff --git a/docs/code_snippets/flag/predefined_flags.py b/docs/code_snippets/flag/predefined_flags.py index fd7d352..b389196 100644 --- a/docs/code_snippets/flag/predefined_flags.py +++ b/docs/code_snippets/flag/predefined_flags.py @@ -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 diff --git a/docs/code_snippets/flag/snippet.py b/docs/code_snippets/flag/snippet.py index cb3441c..a2c24e9 100644 --- a/docs/code_snippets/flag/snippet.py +++ b/docs/code_snippets/flag/snippet.py @@ -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,}$"), ) diff --git a/docs/code_snippets/flag/snippet2.py b/docs/code_snippets/flag/snippet2.py index b36e87c..0620358 100644 --- a/docs/code_snippets/flag/snippet2.py +++ b/docs/code_snippets/flag/snippet2.py @@ -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 diff --git a/docs/code_snippets/flag/snippet3.py b/docs/code_snippets/flag/snippet3.py index bad921a..6d42692 100644 --- a/docs/code_snippets/flag/snippet3.py +++ b/docs/code_snippets/flag/snippet3.py @@ -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 diff --git a/docs/code_snippets/flag/snippet4.py b/docs/code_snippets/flag/snippet4.py index a2cbb4f..3f7f589 100644 --- a/docs/code_snippets/flag/snippet4.py +++ b/docs/code_snippets/flag/snippet4.py @@ -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" diff --git a/docs/code_snippets/flag/snippet5.py b/docs/code_snippets/flag/snippet5.py index e61b8d5..7f91b5f 100644 --- a/docs/code_snippets/flag/snippet5.py +++ b/docs/code_snippets/flag/snippet5.py @@ -5,7 +5,7 @@ short_flag = Flag(name="v", prefix="-") # Отладочное представление print(repr(verbose_flag)) # Flag -print(repr(short_flag)) # Flag +print(repr(short_flag)) # Flag # В интерактивной консоли или отладчике # >>> verbose_flag diff --git a/docs/code_snippets/flags/snippet.py b/docs/code_snippets/flags/snippet.py index 516488b..304ff65 100644 --- a/docs/code_snippets/flags/snippet.py +++ b/docs/code_snippets/flags/snippet.py @@ -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 -) \ No newline at end of file +cmd = Command("start", description="Start the server", flags=flags) diff --git a/docs/code_snippets/flags/snippet2.py b/docs/code_snippets/flags/snippet2.py index 4043302..6c3e6af 100644 --- a/docs/code_snippets/flags/snippet2.py +++ b/docs/code_snippets/flags/snippet2.py @@ -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 \ No newline at end of file +print(len(flags.flags)) # 3 diff --git a/docs/code_snippets/flags/snippet3.py b/docs/code_snippets/flags/snippet3.py index 958ea0d..0514cb2 100644 --- a/docs/code_snippets/flags/snippet3.py +++ b/docs/code_snippets/flags/snippet3.py @@ -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 \ No newline at end of file +print(len(flags.flags)) # 5 diff --git a/docs/code_snippets/flags/snippet4.py b/docs/code_snippets/flags/snippet4.py index bbcd81a..30248cd 100644 --- a/docs/code_snippets/flags/snippet4.py +++ b/docs/code_snippets/flags/snippet4.py @@ -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") \ No newline at end of file + print("Flag not found") diff --git a/docs/code_snippets/flags/snippet5.py b/docs/code_snippets/flags/snippet5.py index 421c2c3..b6577ab 100644 --- a/docs/code_snippets/flags/snippet5.py +++ b/docs/code_snippets/flags/snippet5.py @@ -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}") \ No newline at end of file +print(f"All flags: {flag_names}") diff --git a/docs/code_snippets/flags/snippet6.py b/docs/code_snippets/flags/snippet6.py index 11d5bb1..49645f9 100644 --- a/docs/code_snippets/flags/snippet6.py +++ b/docs/code_snippets/flags/snippet6.py @@ -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 \ No newline at end of file +# third diff --git a/docs/code_snippets/input_flag/snippet1.py b/docs/code_snippets/input_flag/snippet1.py index 9ac88fe..875897e 100644 --- a/docs/code_snippets/input_flag/snippet1.py +++ b/docs/code_snippets/input_flag/snippet1.py @@ -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 ) diff --git a/docs/code_snippets/input_flag/snippet2.py b/docs/code_snippets/input_flag/snippet2.py index 4890d4e..01df300 100644 --- a/docs/code_snippets/input_flag/snippet2.py +++ b/docs/code_snippets/input_flag/snippet2.py @@ -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 ) # Получение строкового представления флага diff --git a/docs/code_snippets/input_flag/snippet3.py b/docs/code_snippets/input_flag/snippet3.py index 8c894c0..17e83ef 100644 --- a/docs/code_snippets/input_flag/snippet3.py +++ b/docs/code_snippets/input_flag/snippet3.py @@ -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 ) # Строковое представление включает значение diff --git a/docs/code_snippets/input_flag/snippet4.py b/docs/code_snippets/input_flag/snippet4.py index 00d61ca..71b16f8 100644 --- a/docs/code_snippets/input_flag/snippet4.py +++ b/docs/code_snippets/input_flag/snippet4.py @@ -4,7 +4,7 @@ flag = InputFlag( name="config", prefix="--", input_value="settings.json", - status=ValidationStatus.VALID + status=ValidationStatus.VALID, ) # Отладочное представление объекта diff --git a/docs/code_snippets/input_flag/snippet5.py b/docs/code_snippets/input_flag/snippet5.py index f37650d..a19a815 100644 --- a/docs/code_snippets/input_flag/snippet5.py +++ b/docs/code_snippets/input_flag/snippet5.py @@ -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 ) # Сравнение по имени (префикс и значение не учитываются) diff --git a/docs/code_snippets/input_flags/snippet1.py b/docs/code_snippets/input_flags/snippet1.py index b21b65d..99826cb 100644 --- a/docs/code_snippets/input_flags/snippet1.py +++ b/docs/code_snippets/input_flags/snippet1.py @@ -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") - diff --git a/docs/code_snippets/input_flags/snippet10.py b/docs/code_snippets/input_flags/snippet10.py index 56da416..955a8c0 100644 --- a/docs/code_snippets/input_flags/snippet10.py +++ b/docs/code_snippets/input_flags/snippet10.py @@ -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}") - diff --git a/docs/code_snippets/input_flags/snippet2.py b/docs/code_snippets/input_flags/snippet2.py index ed7ba3b..eeb2554 100644 --- a/docs/code_snippets/input_flags/snippet2.py +++ b/docs/code_snippets/input_flags/snippet2.py @@ -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") - diff --git a/docs/code_snippets/input_flags/snippet3.py b/docs/code_snippets/input_flags/snippet3.py index ade3d04..7b3eba8 100644 --- a/docs/code_snippets/input_flags/snippet3.py +++ b/docs/code_snippets/input_flags/snippet3.py @@ -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}") - diff --git a/docs/code_snippets/input_flags/snippet4.py b/docs/code_snippets/input_flags/snippet4.py index 8217b73..ada2244 100644 --- a/docs/code_snippets/input_flags/snippet4.py +++ b/docs/code_snippets/input_flags/snippet4.py @@ -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}") - diff --git a/docs/code_snippets/input_flags/snippet5.py b/docs/code_snippets/input_flags/snippet5.py index 3c8cbed..6c69c68 100644 --- a/docs/code_snippets/input_flags/snippet5.py +++ b/docs/code_snippets/input_flags/snippet5.py @@ -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}") - diff --git a/docs/code_snippets/input_flags/snippet6.py b/docs/code_snippets/input_flags/snippet6.py index d33f508..ff8481f 100644 --- a/docs/code_snippets/input_flags/snippet6.py +++ b/docs/code_snippets/input_flags/snippet6.py @@ -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]}") - diff --git a/docs/code_snippets/input_flags/snippet7.py b/docs/code_snippets/input_flags/snippet7.py index 908da25..ebb22a8 100644 --- a/docs/code_snippets/input_flags/snippet7.py +++ b/docs/code_snippets/input_flags/snippet7.py @@ -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}") - diff --git a/docs/code_snippets/input_flags/snippet8.py b/docs/code_snippets/input_flags/snippet8.py index 3798101..6ad898d 100644 --- a/docs/code_snippets/input_flags/snippet8.py +++ b/docs/code_snippets/input_flags/snippet8.py @@ -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 (разные флаги) - diff --git a/docs/code_snippets/input_flags/snippet9.py b/docs/code_snippets/input_flags/snippet9.py index 800d5e6..3b4bc44 100644 --- a/docs/code_snippets/input_flags/snippet9.py +++ b/docs/code_snippets/input_flags/snippet9.py @@ -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") - diff --git a/docs/code_snippets/orchestrator/snippet.py b/docs/code_snippets/orchestrator/snippet.py index 13f9de3..e6cd053 100644 --- a/docs/code_snippets/orchestrator/snippet.py +++ b/docs/code_snippets/orchestrator/snippet.py @@ -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) \ No newline at end of file + orchestrator.start_polling(app) diff --git a/docs/code_snippets/overriding_formatting/sample.py b/docs/code_snippets/overriding_formatting/sample.py index bb3f0c7..160b622 100644 --- a/docs/code_snippets/overriding_formatting/sample.py +++ b/docs/code_snippets/overriding_formatting/sample.py @@ -5,6 +5,7 @@ def custom_print_function(text: str) -> None: """Простая пользовательская функция вывода с префиксом.""" print(f"Префикс: {text}") + app = App( initial_message="My App", override_system_messages=True, diff --git a/docs/code_snippets/possible_values/all.py b/docs/code_snippets/possible_values/all.py index 7436593..7a1ebe5 100644 --- a/docs/code_snippets/possible_values/all.py +++ b/docs/code_snippets/possible_values/all.py @@ -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" diff --git a/docs/code_snippets/possible_values/combined.py b/docs/code_snippets/possible_values/combined.py index 2e599f5..62159ee 100644 --- a/docs/code_snippets/possible_values/combined.py +++ b/docs/code_snippets/possible_values/combined.py @@ -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+$")) diff --git a/docs/code_snippets/possible_values/predefined.py b/docs/code_snippets/possible_values/predefined.py index 79ff23b..66010e1 100644 --- a/docs/code_snippets/possible_values/predefined.py +++ b/docs/code_snippets/possible_values/predefined.py @@ -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 diff --git a/docs/code_snippets/quickstart/main.py b/docs/code_snippets/quickstart/main.py index 7f83a8d..e740d9d 100644 --- a/docs/code_snippets/quickstart/main.py +++ b/docs/code_snippets/quickstart/main.py @@ -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() - \ No newline at end of file diff --git a/docs/code_snippets/quickstart/routers.py b/docs/code_snippets/quickstart/routers.py index c3492f8..a986681 100644 --- a/docs/code_snippets/quickstart/routers.py +++ b/docs/code_snippets/quickstart/routers.py @@ -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!") - \ No newline at end of file diff --git a/docs/code_snippets/quickstart/task_manager/handlers.py b/docs/code_snippets/quickstart/task_manager/handlers.py index ddf5f0c..2345645 100644 --- a/docs/code_snippets/quickstart/task_manager/handlers.py +++ b/docs/code_snippets/quickstart/task_manager/handlers.py @@ -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() diff --git a/docs/code_snippets/quickstart/task_manager/repository.py b/docs/code_snippets/quickstart/task_manager/repository.py index df4ed77..72abbd6 100644 --- a/docs/code_snippets/quickstart/task_manager/repository.py +++ b/docs/code_snippets/quickstart/task_manager/repository.py @@ -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] = [] diff --git a/docs/code_snippets/redirect_stdout/sample.py b/docs/code_snippets/redirect_stdout/sample.py index c571941..51e5f9e 100644 --- a/docs/code_snippets/redirect_stdout/sample.py +++ b/docs/code_snippets/redirect_stdout/sample.py @@ -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}!") \ No newline at end of file + print(f"Приятно познакомиться, {name}!") diff --git a/docs/code_snippets/redirect_stdout/sample2.py b/docs/code_snippets/redirect_stdout/sample2.py index 1229a7d..320d641 100644 --- a/docs/code_snippets/redirect_stdout/sample2.py +++ b/docs/code_snippets/redirect_stdout/sample2.py @@ -3,4 +3,4 @@ from argenta.app.dividing_line import StaticDividingLine # Все роутеры по умолчанию будут использовать статическую линию длиной 50 символов # (если для них не отключен перехват stdout) -app = App(dividing_line=StaticDividingLine(length=50)) \ No newline at end of file +app = App(dividing_line=StaticDividingLine(length=50)) diff --git a/docs/code_snippets/response/snippet1.py b/docs/code_snippets/response/snippet1.py index 2b30f28..ce605b8 100644 --- a/docs/code_snippets/response/snippet1.py +++ b/docs/code_snippets/response/snippet1.py @@ -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.") - diff --git a/docs/code_snippets/response/snippet2.py b/docs/code_snippets/response/snippet2.py index 757620e..141a324 100644 --- a/docs/code_snippets/response/snippet2.py +++ b/docs/code_snippets/response/snippet2.py @@ -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', {})}") - diff --git a/docs/code_snippets/response/snippet3.py b/docs/code_snippets/response/snippet3.py index 3c8a80b..9c76b8d 100644 --- a/docs/code_snippets/response/snippet3.py +++ b/docs/code_snippets/response/snippet3.py @@ -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") - diff --git a/docs/code_snippets/response/snippet4.py b/docs/code_snippets/response/snippet4.py index 8519b05..e5b519e 100644 --- a/docs/code_snippets/response/snippet4.py +++ b/docs/code_snippets/response/snippet4.py @@ -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") - diff --git a/docs/code_snippets/response/snippet5.py b/docs/code_snippets/response/snippet5.py index c735680..0999236 100644 --- a/docs/code_snippets/response/snippet5.py +++ b/docs/code_snippets/response/snippet5.py @@ -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") - diff --git a/docs/code_snippets/response/snippet6.py b/docs/code_snippets/response/snippet6.py index 4981b63..cc75a70 100644 --- a/docs/code_snippets/response/snippet6.py +++ b/docs/code_snippets/response/snippet6.py @@ -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}") - diff --git a/docs/code_snippets/router/snippet.py b/docs/code_snippets/router/snippet.py index 36da713..cbd23d7 100644 --- a/docs/code_snippets/router/snippet.py +++ b/docs/code_snippets/router/snippet.py @@ -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!") \ No newline at end of file + print("User added successfully!") diff --git a/docs/code_snippets/validation_status/comprehensive.py b/docs/code_snippets/validation_status/comprehensive.py index a494e43..7545fd1 100644 --- a/docs/code_snippets/validation_status/comprehensive.py +++ b/docs/code_snippets/validation_status/comprehensive.py @@ -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), ] diff --git a/docs/code_snippets/validation_status/input_flag.py b/docs/code_snippets/validation_status/input_flag.py index 5217d1e..c72a1b6 100644 --- a/docs/code_snippets/validation_status/input_flag.py +++ b/docs/code_snippets/validation_status/input_flag.py @@ -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] diff --git a/docs/code_snippets/validation_status/invalid.py b/docs/code_snippets/validation_status/invalid.py index a924c92..6500364 100644 --- a/docs/code_snippets/validation_status/invalid.py +++ b/docs/code_snippets/validation_status/invalid.py @@ -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) diff --git a/docs/code_snippets/validation_status/processing.py b/docs/code_snippets/validation_status/processing.py index ff0e9a7..6656c9a 100644 --- a/docs/code_snippets/validation_status/processing.py +++ b/docs/code_snippets/validation_status/processing.py @@ -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 diff --git a/docs/code_snippets/validation_status/undefined.py b/docs/code_snippets/validation_status/undefined.py index a3734fe..c827f04 100644 --- a/docs/code_snippets/validation_status/undefined.py +++ b/docs/code_snippets/validation_status/undefined.py @@ -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 +) diff --git a/docs/code_snippets/validation_status/valid.py b/docs/code_snippets/validation_status/valid.py index 4c2659a..c487f90 100644 --- a/docs/code_snippets/validation_status/valid.py +++ b/docs/code_snippets/validation_status/valid.py @@ -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)