Update documentation and code snippets

This commit is contained in:
2025-12-03 14:30:33 +03:00
parent 2a0ec209c3
commit 52139e5405
14 changed files with 484 additions and 200 deletions
+7 -7
View File
@@ -12,31 +12,31 @@ def authenticate_user(username: str) -> str:
def login_handler(response: Response, data_bridge: FromDishka[DataBridge]):
username_flag = response.input_flags.get_flag_by_name("username")
if not username_flag or not username_flag.input_value:
print("Ошибка необходимо указать имя пользователя с помощью флага --username.")
print("Error: username must be specified using the --username flag.")
return
username = username_flag.input_value
token = authenticate_user(username)
data_bridge.update({"auth_token": token})
print(f"Успешный вход! Пользователь '{username}' аутентифицирован.")
print(f"Login successful! User '{username}' authenticated.")
@router.command("get-profile")
def get_profile_handler(response: Response, data_bridge: FromDishka[DataBridge])
def get_profile_handler(response: Response, data_bridge: FromDishka[DataBridge]):
token = data_bridge.get_by_key("auth_token")
if not token:
print("Ошибка: вы не аутентифицированы. Сначала выполните команду 'login'.")
print("Error: you are not authenticated. Please run the 'login' command first.")
return
print(f"Загрузка профиля с использованием токена: [yellow]{token}[/yellow]")
print(f"Loading profile using token: [yellow]{token}[/yellow]")
@router.command("logout")
def logout_handler(response: Response, data_bridge: FromDishka[DataBridge]):
try:
data_bridge.delete_by_key("auth_token")
print("Выход выполнен. Данные сессии очищены.")
print("Logout successful. Session data cleared.")
except KeyError:
print("Вы и так не были аутентифицированы.")
print("You were not authenticated anyway.")
@@ -3,7 +3,6 @@
# This file is distributed under the same license as the Argenta package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Argenta \n"
@@ -30,14 +29,17 @@ msgid ""
"подсказки и завершая ввод на основе истории команд, что ускоряет работу и"
" снижает вероятность опечаток."
msgstr ""
"``AutoCompleter`` is a component responsible for interactive command autocompletion. "
"It improves user experience by offering suggestions and completing input based on "
"command history, which speeds up work and reduces the likelihood of typos."
#: ../../root/api/app/autocompleter.rst:11
msgid "Инициализация"
msgstr ""
msgstr "Initialization"
#: ../../root/api/app/autocompleter.rst:18
msgid "Создаёт и настраивает экземпляр ``AutoCompleter``."
msgstr ""
msgstr "Creates and configures an ``AutoCompleter`` instance."
#: ../../root/api/app/autocompleter.rst:20
msgid ""
@@ -45,20 +47,24 @@ msgid ""
"указано, история будет сохраняться между сессиями. При значении ``None`` "
"история хранится только в контексте сессии."
msgstr ""
"``history_filename``: Filename for saving command history. If specified, history "
"will be saved between sessions. When set to ``None``, history is stored only within "
"the session context."
#: ../../root/api/app/autocompleter.rst:21
msgid ""
"``autocomplete_button``: Клавиша, активирующая автодополнение. По "
"умолчанию — **Tab**."
msgstr ""
"``autocomplete_button``: Key that activates autocompletion. Defaults to **Tab**."
#: ../../root/api/app/autocompleter.rst:26
msgid "Назначение и возможности"
msgstr ""
msgstr "Purpose and Features"
#: ../../root/api/app/autocompleter.rst:28
msgid "Основные возможности ``AutoCompleter``:"
msgstr ""
msgstr "Main features of ``AutoCompleter``:"
#: ../../root/api/app/autocompleter.rst:30
msgid ""
@@ -66,6 +72,8 @@ msgid ""
"умолчанию **Tab**) система ищет в истории команды, начинающиеся с уже "
"введённого текста."
msgstr ""
"**History-based autocompletion**: When the autocompletion key is pressed (by default **Tab**), "
"the system searches history for commands starting with the already entered text."
#: ../../root/api/app/autocompleter.rst:32
msgid ""
@@ -74,6 +82,9 @@ msgid ""
"``show_profile`` при вводе ``sho`` и нажатии **Tab** ввод дополнится до "
"``show_``."
msgstr ""
"**Common prefix**: If multiple commands with a common prefix are found, only the common "
"part will be inserted. For example, for commands ``show_users`` and ``show_profile``, "
"when entering ``sho`` and pressing **Tab**, the input will be completed to ``show_``."
#: ../../root/api/app/autocompleter.rst:34
msgid ""
@@ -81,24 +92,29 @@ msgid ""
"сохраняется в файл при выходе и загружается при следующем запуске. Это "
"делает автодополнение со временем «умнее»."
msgstr ""
"**Persistent history**: If ``history_filename`` is specified, command history is saved "
"to a file on exit and loaded on the next startup. This makes autocompletion \"smarter\" over time."
#: ../../root/api/app/autocompleter.rst:36
msgid ""
"**Очистка истории**: При сохранении ``AutoCompleter`` удаляет дубликаты и"
" несуществующие команды, поддерживая историю в актуальном состоянии."
msgstr ""
"**History cleanup**: When saving, ``AutoCompleter`` removes duplicates and non-existent "
"commands, keeping the history up to date."
#: ../../root/api/app/autocompleter.rst:38
msgid ""
"**Настройка клавиши**: Клавишу автодополнения можно изменить с помощью "
"параметра ``autocomplete_button``."
msgstr ""
"**Key customization**: The autocompletion key can be changed using the ``autocomplete_button`` parameter."
#: ../../root/api/app/autocompleter.rst:43
msgid "Пример использования"
msgstr ""
msgstr "Usage Example"
#: ../../root/api/app/autocompleter.rst:45
msgid "``AutoCompleter`` передаётся как аргумент при инициализации `App`."
msgstr ""
msgstr "``AutoCompleter`` is passed as an argument when initializing `App`."
@@ -21,7 +21,7 @@ msgstr ""
#: ../../root/api/app/dividing_lines.rst:4
msgid "Dividing Lines"
msgstr ""
msgstr "Dividing Lines"
#: ../../root/api/app/dividing_lines.rst:6
msgid ""
@@ -29,10 +29,12 @@ msgid ""
"структурирования вывода и отделения блоков информации друг от друга. "
"Библиотека предлагает два типа линий: статическую и динамическую."
msgstr ""
"Dividing lines in ``Argenta`` are used for visual structuring of output and separating "
"information blocks from each other. The library offers two types of lines: static and dynamic."
#: ../../root/api/app/dividing_lines.rst:11
msgid "``StaticDividingLine``"
msgstr ""
msgstr "``StaticDividingLine``"
#: ../../root/api/app/dividing_lines.rst:13
msgid ""
@@ -40,24 +42,28 @@ msgid ""
"длины. Этот тип линии полезен для создания предсказуемого и "
"унифицированного интерфейса."
msgstr ""
"``StaticDividingLine`` creates a dividing line of **fixed** length. This type of line "
"is useful for creating a predictable and unified interface."
#: ../../root/api/app/dividing_lines.rst:21
msgid "Создаёт экземпляр статической разделительной линии."
msgstr ""
msgstr "Creates a static dividing line instance."
#: ../../root/api/app/dividing_lines.rst:23
msgid ""
"``unit_part``: Символ для построения линии (учитывается только первый "
"символ). По умолчанию: ``-``."
msgstr ""
"``unit_part``: Character for building the line (only the first character is considered). "
"Defaults to: ``-``."
#: ../../root/api/app/dividing_lines.rst:24
msgid "``length``: Фиксированная длина линии. По умолчанию: ``25``."
msgstr ""
msgstr "``length``: Fixed line length. Defaults to: ``25``."
#: ../../root/api/app/dividing_lines.rst:29
msgid "``DynamicDividingLine``"
msgstr ""
msgstr "``DynamicDividingLine``"
#: ../../root/api/app/dividing_lines.rst:31
msgid ""
@@ -66,40 +72,45 @@ msgid ""
"перехвата ``stdout``, в результате чего разделители идеально обрамляют "
"выводимый контент."
msgstr ""
"``DynamicDividingLine`` creates a line whose length **dynamically** adjusts to the longest "
"line in the command output. This requires capturing ``stdout``, resulting in dividers that "
"perfectly frame the output content."
#: ../../root/api/app/dividing_lines.rst:38
msgid "Создаёт экземпляр динамической разделительной линии."
msgstr ""
msgstr "Creates a dynamic dividing line instance."
#: ../../root/api/app/dividing_lines.rst:40
msgid "``unit_part``: Символ для построения линии. По умолчанию: ``-``."
msgstr ""
msgstr "``unit_part``: Character for building the line. Defaults to: ``-``."
#: ../../root/api/app/dividing_lines.rst:42
msgid "Длина вычисляется автоматически и не задаётся при инициализации."
msgstr ""
msgstr "Length is calculated automatically and is not set during initialization."
#: ../../root/api/app/dividing_lines.rst:45
msgid ""
"Обязательно почитайте про нюансы использования динамических линий и "
"перехвата ``stdout`` в :ref:`этом разделе<root_redirect_stdout>`."
msgstr ""
"Be sure to read about the nuances of using dynamic lines and capturing ``stdout`` "
"in :ref:`this section<root_redirect_stdout>`."
#: ../../root/api/app/dividing_lines.rst:50
msgid "Назначение и использование"
msgstr ""
msgstr "Purpose and Usage"
#: ../../root/api/app/dividing_lines.rst:52
msgid "Выбор между статической и динамической линией зависит от ваших задач."
msgstr ""
msgstr "The choice between static and dynamic lines depends on your needs."
#: ../../root/api/app/dividing_lines.rst:54
msgid "**StaticDividingLine** идеально подходит, если:"
msgstr ""
msgstr "**StaticDividingLine** is ideal if:"
#: ../../root/api/app/dividing_lines.rst:56
msgid "Вам нужен строгий и консистентный дизайн."
msgstr ""
msgstr "You need a strict and consistent design."
#: ../../root/api/app/dividing_lines.rst:57
msgid ""
@@ -107,30 +118,34 @@ msgid ""
"(``disable_redirect_stdout=True``), где динамическое вычисление длины "
"невозможно."
msgstr ""
"You are using routers with disabled ``stdout`` capture (``disable_redirect_stdout=True``), "
"where dynamic length calculation is not possible."
#: ../../root/api/app/dividing_lines.rst:59
msgid ""
"**DynamicDividingLine** (поведение по умолчанию) — предпочтительный "
"выбор, если:"
msgstr ""
msgstr "**DynamicDividingLine** (default behavior) is the preferred choice if:"
#: ../../root/api/app/dividing_lines.rst:61
msgid "Вы хотите, чтобы интерфейс был адаптивным."
msgstr ""
msgstr "You want the interface to be adaptive."
#: ../../root/api/app/dividing_lines.rst:62
msgid "Вывод ваших команд имеет разную длину."
msgstr ""
msgstr "Your command output has varying lengths."
#: ../../root/api/app/dividing_lines.rst:63
msgid ""
"В ваших обработчиках нет интерактивных операций ввода (например, "
"``input()``)."
msgstr ""
msgstr "Your handlers do not have interactive input operations (e.g., ``input()``)."
#: ../../root/api/app/dividing_lines.rst:65
msgid ""
"Тип разделителя для всего приложения задаётся при инициализации ``App`` "
"через параметр ``dividing_line``."
msgstr ""
"The divider type for the entire application is set during ``App`` initialization "
"via the ``dividing_line`` parameter."
@@ -3,7 +3,6 @@
# This file is distributed under the same license as the Argenta package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Argenta \n"
@@ -30,180 +29,199 @@ msgid ""
"взаимодействие с пользователем, координируя работу всех компонентов: "
"роутеров, обработчиков и системных сообщений."
msgstr ""
"The ``App`` object is the core of your console application. It handles "
"configuration, lifecycle management, command processing, and user interaction, "
"coordinating the work of all components: routers, handlers, and system messages."
#: ../../root/api/app/index.rst:11
msgid "Инициализация"
msgstr ""
msgstr "Initialization"
#: ../../root/api/app/index.rst:38
msgid "Создаёт и настраивает экземпляр приложения."
msgstr ""
msgstr "Creates and configures an application instance."
#: ../../root/api/app/index.rst:40
msgid "``prompt``: Приглашение к вводу, отображаемое перед каждой командой."
msgstr ""
msgstr "``prompt``: Input prompt displayed before each command."
#: ../../root/api/app/index.rst:41
msgid "``initial_message``: Сообщение, выводимое при запуске приложения."
msgstr ""
msgstr "``initial_message``: Message displayed when the application starts."
#: ../../root/api/app/index.rst:42
msgid "``farewell_message``: Сообщение, выводимое при выходе из приложения."
msgstr ""
msgstr "``farewell_message``: Message displayed when exiting the application."
#: ../../root/api/app/index.rst:43
msgid ""
"``exit_command``: Команда, которая маркируется как триггер для выхода из "
"приложения."
msgstr ""
"``exit_command``: Command that is marked as a trigger for exiting the application."
#: ../../root/api/app/index.rst:44
msgid ""
"``system_router_title``: Заголовок для системного роутера (содержит "
"команду выхода)."
msgstr ""
"``system_router_title``: Title for the system router (contains the exit command)."
#: ../../root/api/app/index.rst:45
msgid ""
"``ignore_command_register``: Если ``True``, регистр вводимых команд "
"игнорируется при поиске обработчика."
msgstr ""
"``ignore_command_register``: If ``True``, command case is ignored when searching for a handler."
#: ../../root/api/app/index.rst:46
msgid ""
"``dividing_line``: Тип разделительной линии (``StaticDividingLine`` или "
"``DynamicDividingLine``)."
msgstr ""
"``dividing_line``: Type of dividing line (``StaticDividingLine`` or ``DynamicDividingLine``)."
#: ../../root/api/app/index.rst:47
msgid ""
"``repeat_command_groups_printing``: Если ``True``, список доступных "
"команд выводится перед каждым вводом."
msgstr ""
"``repeat_command_groups_printing``: If ``True``, the list of available commands is displayed before each input."
#: ../../root/api/app/index.rst:48
msgid ""
"``override_system_messages``: Если ``True``, стандартное форматирование "
"(цвета, ASCII-арт) отключается."
msgstr ""
"``override_system_messages``: If ``True``, standard formatting (colors, ASCII art) is disabled."
#: ../../root/api/app/index.rst:49
msgid ""
"``autocompleter``: Экземпляр класса :ref:`AutoCompleter "
"<root_api_app_autocompleter>`, отвечающий за автодополнение команд."
msgstr ""
"``autocompleter``: Instance of the :ref:`AutoCompleter <root_api_app_autocompleter>` "
"class responsible for command autocompletion."
#: ../../root/api/app/index.rst:50
msgid ""
"``print_func``: Функция для вывода всех системных сообщений (по умолчанию"
" ``rich.Console().print``)."
msgstr ""
"``print_func``: Function for outputting all system messages (defaults to ``rich.Console().print``)."
#: ../../root/api/app/index.rst:55
msgid "Основные методы"
msgstr ""
msgstr "Main Methods"
#: ../../root/api/app/index.rst:59
msgid ""
"Регистрирует роутер в приложении. Все команды из этого роутера становятся"
" доступными для вызова."
msgstr ""
"Registers a router in the application. All commands from this router become available for invocation."
#: ../../root/api/app/index.rst
msgid "Parameters"
msgstr ""
msgstr "Parameters"
#: ../../root/api/app/index.rst:61
msgid "Экземпляр ``Router`` для регистрации."
msgstr ""
msgstr "``Router`` instance to register."
#: ../../root/api/app/index.rst:65
msgid "Регистрирует несколько роутеров одновременно."
msgstr ""
msgstr "Registers multiple routers simultaneously."
#: ../../root/api/app/index.rst:67
msgid "Последовательность экземпляров ``Router`` для регистрации."
msgstr ""
msgstr "Sequence of ``Router`` instances to register."
#: ../../root/api/app/index.rst:71
msgid ""
"Добавляет текстовое сообщение, которое выводится при запуске приложения "
"после ``initial_message``."
msgstr ""
"Adds a text message that is displayed when the application starts after ``initial_message``."
#: ../../root/api/app/index.rst:73
msgid "Строка с сообщением."
msgstr ""
msgstr "String with the message."
#: ../../root/api/app/index.rst:76
msgid ""
"Для вывода стандартных сообщений можно использовать готовые шаблоны из "
":ref:`PredefinedMessages <root_api_predefined_messages>`."
msgstr ""
"For outputting standard messages, you can use ready-made templates from "
":ref:`PredefinedMessages <root_api_predefined_messages>`."
#: ../../root/api/app/index.rst:81
msgid "Методы установки обработчиков"
msgstr ""
msgstr "Handler Setup Methods"
#: ../../root/api/app/index.rst:83
msgid ""
"``App`` позволяет настраивать реакцию на различные события, такие как "
"ошибки ввода или неизвестные команды."
msgstr ""
"``App`` allows you to configure responses to various events, such as input errors or unknown commands."
#: ../../root/api/app/index.rst:86
msgid ""
"Подробнее о исключениях и их обработке в соответствующем :ref:`разделе "
"документации <root_error_handling>`."
msgstr ""
"For more details on exceptions and their handling, see the corresponding "
":ref:`documentation section <root_error_handling>`."
#: ../../root/api/app/index.rst:92
msgid "Устанавливает шаблон для форматирования описания команды."
msgstr ""
msgstr "Sets the template for formatting command descriptions."
#: ../../root/api/app/index.rst:94
msgid "Обработчик принимает триггер команды (``str``) и её описание (``str``)."
msgstr ""
msgstr "The handler accepts the command trigger (``str``) and its description (``str``)."
#: ../../root/api/app/index.rst:100
msgid "Устанавливает обработчик при некорректном введённом синтаксисе флагов."
msgstr ""
msgstr "Sets the handler for incorrect flag syntax input."
#: ../../root/api/app/index.rst:102 ../../root/api/app/index.rst:110
msgid "Обработчик принимает строку, введённую пользователем."
msgstr ""
msgstr "The handler accepts the string entered by the user."
#: ../../root/api/app/index.rst:108
msgid "Устанавливает обработчик при повторяющихся флагах в введённой команде."
msgstr ""
msgstr "Sets the handler for duplicate flags in the entered command."
#: ../../root/api/app/index.rst:116
msgid "Устанавливает обработчик при вводе неизвестной команды."
msgstr ""
msgstr "Sets the handler for entering an unknown command."
#: ../../root/api/app/index.rst:118
msgid "Обработчик принимает объект ``InputCommand`` - объект введённой команды."
msgstr ""
msgstr "The handler accepts an ``InputCommand`` object - the entered command object."
#: ../../root/api/app/index.rst:124
msgid "Устанавливает обработчик при вводе пустой строки."
msgstr ""
msgstr "Sets the handler for entering an empty string."
#: ../../root/api/app/index.rst:126
msgid "Обработчик не принимает аргументов."
msgstr ""
msgstr "The handler accepts no arguments."
#: ../../root/api/app/index.rst:132
msgid "Переопределяет стандартное поведение при вызове команды выхода."
msgstr ""
msgstr "Overrides the default behavior when the exit command is invoked."
#: ../../root/api/app/index.rst:134
msgid "Обработчик принимает объект ``Response``."
msgstr ""
msgstr "The handler accepts a ``Response`` object."
#: ../../root/api/app/index.rst:147
msgid "PredefinedMessages"
msgstr ""
msgstr "PredefinedMessages"
#: ../../root/api/app/index.rst:149
msgid ""
@@ -212,32 +230,35 @@ msgid ""
"``rich`` и предназначены для вывода стандартной информации, такой как "
"подсказки по использованию."
msgstr ""
"``PredefinedMessages`` is a container containing a set of ready-to-use messages. "
"They are formatted using ``rich`` syntax and are intended for displaying standard "
"information, such as usage hints."
#: ../../root/api/app/index.rst:151
msgid "Реккомендуется использовать их при старте приложения."
msgstr ""
msgstr "It is recommended to use them when starting the application."
#: ../../root/api/app/index.rst:178
msgid "Строка: ``[b dim]Usage[/b dim]: [i]<command> <[green]flags[/green]>[/i]``"
msgstr ""
msgstr "String: ``[b dim]Usage[/b dim]: [i]<command> <[green]flags[/green]>[/i]``"
#: ../../root/api/app/index.rst:180
msgid "Отображается как: ``Usage: <command> <flags>``"
msgstr ""
msgstr "Displayed as: ``Usage: <command> <flags>``"
#: ../../root/api/app/index.rst:184
msgid "Строка: ``[b dim]Help[/b dim]: [i]<command>[/i] [b red]--help[/b red]``"
msgstr ""
msgstr "String: ``[b dim]Help[/b dim]: [i]<command>[/i] [b red]--help[/b red]``"
#: ../../root/api/app/index.rst:186
msgid "Отображается как: ``Help: <command> --help``"
msgstr ""
msgstr "Displayed as: ``Help: <command> --help``"
#: ../../root/api/app/index.rst:190
msgid "Строка: ``[b dim]Autocomplete[/b dim]: [i]<part>[/i] [bold]<tab>``"
msgstr ""
msgstr "String: ``[b dim]Autocomplete[/b dim]: [i]<part>[/i] [bold]<tab>``"
#: ../../root/api/app/index.rst:192
msgid "Отображается как: ``Autocomplete: <part> <tab>``"
msgstr ""
msgstr "Displayed as: ``Autocomplete: <part> <tab>``"
+20 -12
View File
@@ -3,7 +3,6 @@
# This file is distributed under the same license as the Argenta package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Argenta \n"
@@ -21,7 +20,7 @@ msgstr ""
#: ../../root/api/bridge.rst:4
msgid "DataBridge"
msgstr ""
msgstr "DataBridge"
#: ../../root/api/bridge.rst:6
msgid ""
@@ -29,66 +28,75 @@ msgid ""
"данных, которое существует в рамках одной сессии приложения (от запуска "
"до выхода). Она предназначена для обмена данными между обработчиками."
msgstr ""
"``DataBridge`` is an entity that provides temporary data storage that exists within "
"a single application session (from startup to exit). It is designed for data "
"exchange between handlers."
#: ../../root/api/bridge.rst:8
msgid "Основной способ получения доступа к ``DataBridge`` — через ``di``."
msgstr ""
msgstr "The main way to access ``DataBridge`` is through ``di``."
#: ../../root/api/bridge.rst:21
msgid "**Практический пример: Аутентификация**"
msgstr ""
msgstr "**Practical Example: Authentication**"
#: ../../root/api/bridge.rst:23
msgid ""
"Рассмотрим пример, где команда `login` сохраняет токен аутентификации, а "
"команда `get-profile` использует его."
msgstr ""
"Let's consider an example where the `login` command saves an authentication token, "
"and the `get-profile` command uses it."
#: ../../root/api/bridge.rst:29
msgid "**Как это работает:**"
msgstr ""
msgstr "**How it works:**"
#: ../../root/api/bridge.rst:31
msgid ""
"При вызове обработчика ``dishka`` автоматически внедряет экземпляр "
"``DataBridge``."
msgstr ""
msgstr "When calling a handler, ``dishka`` automatically injects a ``DataBridge`` instance."
#: ../../root/api/bridge.rst:32
msgid ""
"Команда ``login --username <имя>`` вызывает ``login_handler``, который "
"через внедрённый ``data_bridge`` сохраняет токен."
msgstr ""
"The ``login --username <name>`` command calls ``login_handler``, which saves the "
"token through the injected ``data_bridge``."
#: ../../root/api/bridge.rst:33
msgid ""
"Команда ``get-profile`` вызывает ``get_profile_handler``, который так же "
"получает ``data_bridge`` и извлекает из него токен."
msgstr ""
"The ``get-profile`` command calls ``get_profile_handler``, which also receives "
"``data_bridge`` and extracts the token from it."
#: ../../root/api/bridge.rst:42
msgid ""
"Инициализирует хранилище. При использовании через ``di`` вызывается "
"автоматически."
msgstr ""
msgstr "Initializes the storage. When used through ``di``, it is called automatically."
#: ../../root/api/bridge.rst:46
msgid "Обновляет хранилище данными из словаря."
msgstr ""
msgstr "Updates the storage with data from a dictionary."
#: ../../root/api/bridge.rst:50
msgid "Возвращает все данные из хранилища."
msgstr ""
msgstr "Returns all data from the storage."
#: ../../root/api/bridge.rst:54
msgid "Возвращает значение по ключу или ``None``, если ключ не найден."
msgstr ""
msgstr "Returns the value by key or ``None`` if the key is not found."
#: ../../root/api/bridge.rst:58
msgid "Удаляет значение по ключу. Вызывает ``KeyError``, если ключ не найден."
msgstr ""
msgstr "Deletes the value by key. Raises ``KeyError`` if the key is not found."
#: ../../root/api/bridge.rst:62
msgid "Полностью очищает хранилище."
msgstr ""
msgstr "Completely clears the storage."
+48 -19
View File
@@ -3,7 +3,6 @@
# This file is distributed under the same license as the Argenta package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Argenta \n"
@@ -21,31 +20,31 @@ msgstr ""
#: ../../root/api/index.rst:5
msgid "Публичное API"
msgstr ""
msgstr "Public API"
#: ../../root/api/index.rst:8
msgid "Описание раздела"
msgstr ""
msgstr "Section Description"
#: ../../root/api/index.rst:10
msgid "В этом разделе описан публичный API библиотеки. Он включает:"
msgstr ""
msgstr "This section describes the library's public API. It includes:"
#: ../../root/api/index.rst:12
msgid "Классы и функции для интеграции в ваши приложения."
msgstr ""
msgstr "Classes and functions for integration into your applications."
#: ../../root/api/index.rst:13
msgid "Рекомендации по использованию и поддерживаемые сценарии."
msgstr ""
msgstr "Usage recommendations and supported scenarios."
#: ../../root/api/index.rst:14
msgid "Примеры кода, подробные сигнатуры и описание возвращаемых значений."
msgstr ""
msgstr "Code examples, detailed signatures, and descriptions of return values."
#: ../../root/api/index.rst:15
msgid "Гарантии стабильности и обратной совместимости."
msgstr ""
msgstr "Stability and backward compatibility guarantees."
#: ../../root/api/index.rst:17
msgid ""
@@ -55,134 +54,164 @@ msgid ""
"здесь. Это обеспечит стабильность и совместимость ваших продуктов с "
"будущими версиями ``Argenta``."
msgstr ""
"Interfaces not described in this section are considered internal. Using them may "
"lead to errors when updating the library. When developing your own solutions, use "
"only the components described here. This will ensure the stability and compatibility "
"of your products with future versions of ``Argenta``."
#: ../../root/api/index.rst:22
msgid "Публичные импорты"
msgstr ""
msgstr "Public Imports"
#: ../../root/api/index.rst:24
msgid ""
"Все основные компоненты библиотеки доступны для прямого импорта из "
"корневого пакета ``argenta`` или его подмодулей."
msgstr ""
"All main library components are available for direct import from the root package "
"``argenta`` or its submodules."
#: ../../root/api/index.rst:27
msgid "Основные компоненты"
msgstr ""
msgstr "Main Components"
#: ../../root/api/index.rst:32
msgid ""
":ref:`App <root_api_app_index>` — Объект приложения, который отвечает за "
"логику роутинга, настройки, валидации и т.д."
msgstr ""
":ref:`App <root_api_app_index>` — Application object responsible for routing logic, "
"settings, validation, etc."
#: ../../root/api/index.rst:33
msgid ""
":ref:`Orchestrator <root_api_orchestrator_index>` — Класс для "
"конфигурирования и запуска всего приложения."
msgstr ""
":ref:`Orchestrator <root_api_orchestrator_index>` — Class for configuring and "
"launching the entire application."
#: ../../root/api/index.rst:34
msgid ""
":ref:`Router <root_api_router>` — Класс для группировки и регистрации "
"команд."
msgstr ""
msgstr ":ref:`Router <root_api_router>` — Class for grouping and registering commands."
#: ../../root/api/index.rst:35
msgid ""
":ref:`Command <root_api_command_index>` — Класс для создания команд при "
"инициализации хэндлеров."
msgstr ""
":ref:`Command <root_api_command_index>` — Class for creating commands when "
"initializing handlers."
#: ../../root/api/index.rst:36
msgid ""
":ref:`Response <root_api_response>` — Объект ответа, передаваемый в "
"обработчики."
msgstr ""
msgstr ":ref:`Response <root_api_response>` — Response object passed to handlers."
#: ../../root/api/index.rst:39
msgid "Команды и флаги"
msgstr ""
msgstr "Commands and Flags"
#: ../../root/api/index.rst:52
msgid ":ref:`Flag <root_api_command_flag>` — Класс для описания флага."
msgstr ""
msgstr ":ref:`Flag <root_api_command_flag>` — Class for describing a flag."
#: ../../root/api/index.rst:53
msgid ":ref:`Flags <root_api_command_flags>` — Коллекция для регистрации флагов."
msgstr ""
msgstr ":ref:`Flags <root_api_command_flags>` — Collection for registering flags."
#: ../../root/api/index.rst:54
msgid ""
":ref:`InputFlag <root_api_command_input_flag>` — Класс для введённого "
"пользователем флага."
msgstr ""
":ref:`InputFlag <root_api_command_input_flag>` — Class for a user-entered flag."
#: ../../root/api/index.rst:55
msgid ""
":ref:`InputFlags <root_api_command_input_flags>` — Коллекция введённых "
"флагов."
msgstr ""
msgstr ":ref:`InputFlags <root_api_command_input_flags>` — Collection of entered flags."
#: ../../root/api/index.rst:56
msgid ""
":ref:`PossibleValues <root_api_command_possible_values>` — Правила "
"валидации значений флага."
msgstr ""
":ref:`PossibleValues <root_api_command_possible_values>` — Validation rules for "
"flag values."
#: ../../root/api/index.rst:57
msgid ""
":ref:`ValidationStatus <root_api_command_validation_status>` — Статусы "
"валидации флагов."
msgstr ""
":ref:`ValidationStatus <root_api_command_validation_status>` — Flag validation statuses."
#: ../../root/api/index.rst:58
msgid ""
":ref:`PredefinedFlags <root_api_command_flag_predefined_flags>` — "
"Коллекция предопределённых флагов."
msgstr ""
":ref:`PredefinedFlags <root_api_command_flag_predefined_flags>` — Collection of "
"predefined flags."
#: ../../root/api/index.rst:61
msgid "Настройка приложения"
msgstr ""
msgstr "Application Configuration"
#: ../../root/api/index.rst:71
msgid ""
":ref:`AutoCompleter <root_api_app_autocompleter>` - Класс для настройки "
"автодополнения."
msgstr ""
":ref:`AutoCompleter <root_api_app_autocompleter>` - Class for configuring "
"autocompletion."
#: ../../root/api/index.rst:72
msgid ""
":ref:`StaticDividingLine <root_api_app_dividing_lines>` — Статическая "
"разделительная линия для оформления вывода."
msgstr ""
":ref:`StaticDividingLine <root_api_app_dividing_lines>` — Static dividing line for "
"output formatting."
#: ../../root/api/index.rst:73
#: ../../root/api/index.rst:73
msgid ""
":ref:`DynamicDividingLine <root_api_app_dividing_lines>` — Динамическая "
"разделительная линия для оформления вывода."
msgstr ""
":ref:`DynamicDividingLine <root_api_app_dividing_lines>` — Dynamic dividing line "
"for output formatting."
#: ../../root/api/index.rst:74
msgid ""
":ref:`PredefinedMessages <root_api_predefined_messages>` — Готовые "
"сообщения для вывода при старте приложения."
msgstr ""
":ref:`PredefinedMessages <root_api_predefined_messages>` — Ready-made messages for "
"output at application startup."
#: ../../root/api/index.rst:77
msgid "Внедрение зависимостей"
msgstr ""
msgstr "Dependency Injection"
#: ../../root/api/index.rst:85
msgid ""
":ref:`FromDishka <root_dependency_injection>` — Маркер аргумента функции "
"как зависимости, которая должна быть инжектирована."
msgstr ""
":ref:`FromDishka <root_dependency_injection>` — Marker for a function argument as a "
"dependency that should be injected."
#: ../../root/api/index.rst:86
msgid ""
":ref:`inject <root_dependency_injection>` — Декоратор для инжектирования "
"зависимостей, указанных в сигнатуре."
msgstr ""
":ref:`inject <root_dependency_injection>` — Decorator for injecting dependencies "
"specified in the signature."
@@ -3,7 +3,6 @@
# This file is distributed under the same license as the Argenta package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Argenta \n"
@@ -21,7 +20,7 @@ msgstr ""
#: ../../root/api/response.rst:4
msgid "Response"
msgstr ""
msgstr "Response"
#: ../../root/api/response.rst:6
msgid ""
@@ -29,44 +28,52 @@ msgid ""
"создаётся автоматически при обработке пользовательского ввода и содержит "
"статус валидации, введённые флаги."
msgstr ""
"``Response`` is an object that is passed to the command handler. It is created "
"automatically when processing user input and contains validation status and entered flags."
#: ../../root/api/response.rst:11
msgid ""
"Документация по :ref:`InputFlags <root_api_command_input_flags>` — "
"коллекция введённых флагов команды."
msgstr ""
"Documentation for :ref:`InputFlags <root_api_command_input_flags>` — collection of "
"entered command flags."
#: ../../root/api/response.rst:13
msgid ""
"Документация по :ref:`ResponseStatus <root_api_response_status>` — "
"статусы валидации флагов команды."
msgstr ""
"Documentation for :ref:`ResponseStatus <root_api_response_status>` — command flag "
"validation statuses."
#: ../../root/api/response.rst:15
msgid ""
"Документация по :ref:`InputFlag <root_api_command_input_flag>` — "
"отдельный введённый флаг."
msgstr ""
"Documentation for :ref:`InputFlag <root_api_command_input_flag>` — individual "
"entered flag."
#: ../../root/api/response.rst:20
msgid "Инициализация"
msgstr ""
msgstr "Initialization"
#: ../../root/api/response.rst:30
msgid "Создаёт новый объект ответа."
msgstr ""
msgstr "Creates a new response object."
#: ../../root/api/response.rst:32
msgid ""
"``status``: Общий статус валидации флагов из перечисления "
"``ResponseStatus``."
msgstr ""
msgstr "``status``: Overall flag validation status from the ``ResponseStatus`` enumeration."
#: ../../root/api/response.rst:33
msgid ""
"``input_flags``: Коллекция введённых флагов (``InputFlags``). По "
"умолчанию — пустая."
msgstr ""
msgstr "``input_flags``: Collection of entered flags (``InputFlags``). Empty by default."
#: ../../root/api/response.rst:36
msgid ""
@@ -74,10 +81,12 @@ msgid ""
"автоматически формируются системой и передаются в обработчик команды в "
"качестве первого обязательного аргумента."
msgstr ""
"Instances of this class are not intended for direct creation. They are automatically "
"formed by the system and passed to the command handler as the first required argument."
#: ../../root/api/response.rst:38
msgid "**Атрибуты:**"
msgstr ""
msgstr "**Attributes:**"
#: ../../root/api/response.rst:43
msgid ""
@@ -85,20 +94,24 @@ msgid ""
"Указывает, были ли среди введённых флагов некорректные или "
"незарегистрированные."
msgstr ""
"Overall validation status of all command flags (``ResponseStatus``). Indicates "
"whether there were any incorrect or unregistered flags among the entered ones."
#: ../../root/api/response.rst:48
msgid ""
"Коллекция всех флагов, переданных с командой (``InputFlags``). Содержит "
"все обработанные флаги с их значениями и статусами валидации."
msgstr ""
"Collection of all flags passed with the command (``InputFlags``). Contains all "
"processed flags with their values and validation statuses."
#: ../../root/api/response.rst:50
msgid "**Пример использования:**"
msgstr ""
msgstr "**Usage example:**"
#: ../../root/api/response.rst:59
msgid "Работа с флагами"
msgstr ""
msgstr "Working with Flags"
#: ../../root/api/response.rst:61
msgid ""
@@ -106,14 +119,16 @@ msgid ""
"``input_flags``. Вы можете проверять их наличие, получать значения и "
"статусы валидации."
msgstr ""
"``Response`` provides access to entered flags through the ``input_flags`` attribute. "
"You can check their presence, get values, and validation statuses."
#: ../../root/api/response.rst:63
msgid "**Пример работы с флагами:**"
msgstr ""
msgstr "**Example of working with flags:**"
#: ../../root/api/response.rst:74
msgid "ResponseStatus"
msgstr ""
msgstr "ResponseStatus"
#: ../../root/api/response.rst:76
msgid ""
@@ -121,6 +136,8 @@ msgid ""
"валидации всех флагов команды. Используется в атрибуте ``status`` объекта"
" ``Response``."
msgstr ""
"``ResponseStatus`` is an enumeration that defines the overall validation status of "
"all command flags. Used in the ``status`` attribute of the ``Response`` object."
#: ../../root/api/response.rst:79
msgid "ALL_FLAGS_VALID"
@@ -131,6 +148,7 @@ msgid ""
"Все введённые флаги прошли валидацию. Нет ни некорректных, ни "
"незарегистрированных флагов."
msgstr ""
"All entered flags passed validation. There are no incorrect or unregistered flags."
#: ../../root/api/response.rst:89
msgid "UNDEFINED_FLAGS"
@@ -141,6 +159,7 @@ msgid ""
"Среди введённых флагов есть незарегистрированные, но нет флагов с "
"некорректными значениями."
msgstr ""
"Among the entered flags, there are unregistered ones, but no flags with incorrect values."
#: ../../root/api/response.rst:99
msgid "INVALID_VALUE_FLAGS"
@@ -151,6 +170,7 @@ msgid ""
"Среди введённых флагов есть флаги с некорректными значениями, но нет "
"незарегистрированных."
msgstr ""
"Among the entered flags, there are flags with incorrect values, but no unregistered ones."
#: ../../root/api/response.rst:109
msgid "UNDEFINED_AND_INVALID_FLAGS"
@@ -161,4 +181,5 @@ msgid ""
"Среди введённых флагов есть как незарегистрированные, так и флаги с "
"некорректными значениями."
msgstr ""
"Among the entered flags, there are both unregistered flags and flags with incorrect values."
+41 -12
View File
@@ -3,7 +3,6 @@
# This file is distributed under the same license as the Argenta package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Argenta \n"
@@ -30,6 +29,9 @@ msgid ""
" Каждый роутер представляет собой логический контейнер для определённого "
"набора функций."
msgstr ""
"``Router`` is the main building block for organizing logic in an "
"application. Its purpose is to group related commands and their handlers. "
"Each router represents a logical container for a specific set of functions."
#: ../../root/api/router.rst:8
msgid ""
@@ -37,20 +39,25 @@ msgid ""
"отвечать за аутентификацию (``login``, ``logout``), а другой — за "
"операции с профилем (``profile-show``, ``profile-edit``)."
msgstr ""
"For example, in a user management application, one router can handle "
"authentication (``login``, ``logout``), while another handles profile "
"operations (``profile-show``, ``profile-edit``)."
#: ../../root/api/router.rst:13
msgid "Инициализация"
msgstr ""
msgstr "Initialization"
#: ../../root/api/router.rst:21
msgid "Создаёт новый экземпляр роутера."
msgstr ""
msgstr "Creates a new router instance."
#: ../../root/api/router.rst:23
msgid ""
"``title``: Необязательный заголовок для группы команд. Отображается в "
"списке доступных команд, помогая пользователю ориентироваться."
msgstr ""
"``title``: Optional title for the command group. Displayed in the list of "
"available commands to help users navigate."
#: ../../root/api/router.rst:24
msgid ""
@@ -60,24 +67,30 @@ msgid ""
"используется статическая разделительная линия. Подробнее см. в разделе "
":ref:`Переопределение стандартного вывода <root_redirect_stdout>`."
msgstr ""
"``disable_redirect_stdout``: If ``True``, disables ``stdout`` capture for "
"all commands in this router. This is necessary for interactive commands "
"(e.g., with ``input()``). When capture is disabled, a static separator line "
"is automatically used. See :ref:`Overriding standard output <root_redirect_stdout>` "
"for more details."
#: ../../root/api/router.rst:29
msgid "Регистрация команд"
msgstr ""
msgstr "Command Registration"
#: ../../root/api/router.rst:31
msgid ""
"Для регистрации команды и привязки к ней обработчика используется "
"декоратор ``@command``."
msgstr ""
"The ``@command`` decorator is used to register a command and bind a handler to it."
#: ../../root/api/router.rst:35
msgid "Декоратор для регистрации функции как обработчика команды."
msgstr ""
msgstr "Decorator for registering a function as a command handler."
#: ../../root/api/router.rst
msgid "Parameters"
msgstr ""
msgstr "Parameters"
#: ../../root/api/router.rst:37
msgid ""
@@ -85,20 +98,25 @@ msgid ""
"Может быть строкой, которая станет триггером (без возможности настройки "
"флагов и описания)."
msgstr ""
"A ``Command`` instance describing the trigger, flags, and command description. "
"Can be a string that will become the trigger (without the ability to configure "
"flags and description)."
#: ../../root/api/router.rst:39
msgid "**Пример использования:**"
msgstr ""
msgstr "**Usage example:**"
#: ../../root/api/router.rst:48
msgid "Системный роутер"
msgstr ""
msgstr "System Router"
#: ../../root/api/router.rst:50
msgid ""
"``Argenta`` поставляется со встроенным системным роутером, который "
"автоматически подключается к каждому приложению."
msgstr ""
"``Argenta`` comes with a built-in system router that is automatically "
"connected to every application."
#: ../../root/api/router.rst:55
msgid ""
@@ -106,6 +124,9 @@ msgid ""
" умолчанию — команда выхода). Имеет заголовок **«System points:»**, "
"который можно переопределить в ``App``."
msgstr ""
"A predefined ``Router`` instance with basic system commands (by default, "
"the exit command). Has the title **\"System points:\"**, which can be "
"overridden in ``App``."
#: ../../root/api/router.rst:57
msgid ""
@@ -113,30 +134,35 @@ msgid ""
"``argenta.router.defaults.system_router`` и используйте его декоратор "
"``@command``."
msgstr ""
"You can add your own commands to this router. To do this, import "
"``argenta.router.defaults.system_router`` and use its ``@command`` decorator."
#: ../../root/api/router.rst:62
msgid "Возможные исключения"
msgstr ""
msgstr "Possible Exceptions"
#: ../../root/api/router.rst:64
msgid ""
"При регистрации команд и флагов в ``Router`` могут возникнуть следующие "
"исключения:"
msgstr ""
"The following exceptions may occur when registering commands and flags in ``Router``:"
#: ../../root/api/router.rst:68
msgid ""
"Выбрасывается, если триггер команды в ``Command`` содержит пробелы. "
"Триггеры должны быть одним словом."
msgstr ""
"Raised if the command trigger in ``Command`` contains spaces. "
"Triggers must be a single word."
#: ../../root/api/router.rst:70
msgid "**Неправильно:** ``Command(\"add user\")``"
msgstr ""
msgstr "**Incorrect:** ``Command(\"add user\")``"
#: ../../root/api/router.rst:72
msgid "**Правильно:** ``Command(\"add-user\")``"
msgstr ""
msgstr "**Correct:** ``Command(\"add-user\")``"
#: ../../root/api/router.rst:76
msgid ""
@@ -144,14 +170,17 @@ msgid ""
"дублирующиеся имена. Имена флагов в рамках одной команды должны быть "
"уникальны."
msgstr ""
"Raised if duplicate names were used when defining flags for a command. "
"Flag names within a single command must be unique."
#: ../../root/api/router.rst:78
msgid "**Пример, вызывающий исключение:**"
msgstr ""
msgstr "**Example that raises an exception:**"
#: ../../root/api/router.rst:90
msgid ""
"Возникает, если обработчик команды не принимает обязательный аргумент "
"``Response``."
msgstr ""
"Raised if the command handler does not accept the required ``Response`` argument."
+89 -33
View File
@@ -3,7 +3,6 @@
# This file is distributed under the same license as the Argenta package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Argenta \n"
@@ -21,21 +20,22 @@ msgstr ""
#: ../../root/flags.rst:4
msgid "Флаги вводимых команд"
msgstr ""
msgstr "Input Command Flags"
#: ../../root/flags.rst:6
msgid ""
"Флаги — это специальные параметры, которые пользователь может добавлять к"
" командам для управления их поведением."
msgstr ""
"Flags are special parameters that users can add to commands to control their behavior."
#: ../../root/flags.rst:9
msgid "Зачем нужны флаги в командах"
msgstr ""
msgstr "Why Flags Are Needed in Commands"
#: ../../root/flags.rst:12
msgid "Управление поведением команды"
msgstr ""
msgstr "Controlling Command Behavior"
#: ../../root/flags.rst:14
msgid ""
@@ -45,10 +45,14 @@ msgid ""
"режимы по требованию пользователя, оставляя основную функциональность "
"неизменной."
msgstr ""
"The main purpose of flags is to provide a way to change the command's logic without "
"reworking it. A command can operate in several modes: standard, verbose, debug, or "
"simplified. Flags switch these modes on user demand, keeping the core functionality "
"unchanged."
#: ../../root/flags.rst:17
msgid "Опциональность и удобство"
msgstr ""
msgstr "Optionality and Convenience"
#: ../../root/flags.rst:19
msgid ""
@@ -57,14 +61,17 @@ msgid ""
" же позволяют задать значения только необходимые в конкретной ситуации, "
"остальные используют значения по умолчанию."
msgstr ""
"Flags solve the problem of mandatory parameters. If all command parameters are made "
"required, it makes the command difficult to use. Flags allow you to specify only "
"the values needed in a specific situation, while others use default values."
#: ../../root/flags.rst:22
msgid "Когда могут понадобиться флаги"
msgstr ""
msgstr "When Flags Might Be Needed"
#: ../../root/flags.rst:24
msgid "**Переключение режимов работы**"
msgstr ""
msgstr "**Switching Operation Modes**"
#: ../../root/flags.rst:25
msgid ""
@@ -72,10 +79,12 @@ msgid ""
"фактического развёртывания (dry-run) для проверки. Флаг ``--dry-run`` "
"переключит режим работы."
msgstr ""
"A command deploys an application normally, but a mode without actual deployment "
"(dry-run) is needed for verification. The ``--dry-run`` flag will switch the mode."
#: ../../root/flags.rst:27
msgid "**Настройка уровня детальности**"
msgstr ""
msgstr "**Adjusting Verbosity Level**"
#: ../../root/flags.rst:28
msgid ""
@@ -83,40 +92,48 @@ msgid ""
" команды. Флаги ``--verbose`` или ``--debug`` предоставляют подробный "
"вывод."
msgstr ""
"When debugging or analyzing, more information about the command execution process "
"is required. The ``--verbose`` or ``--debug`` flags provide detailed output."
#: ../../root/flags.rst:30
msgid "**Управление поведением при ошибках**"
msgstr ""
msgstr "**Managing Error Behavior**"
#: ../../root/flags.rst:31
msgid ""
"По умолчанию команда может прерваться при первой ошибке. Флаг ``--force``"
" позволит продолжить работу, пропуская некритичные ошибки."
msgstr ""
"By default, a command may abort on the first error. The ``--force`` flag allows "
"continuing execution, skipping non-critical errors."
#: ../../root/flags.rst:33
msgid "**Форматирование вывода**"
msgstr ""
msgstr "**Output Formatting**"
#: ../../root/flags.rst:34
msgid ""
"Команда выводит данные текстом, но в некоторых сценариях нужен JSON или "
"CSV. Флаг ``--format=json`` переключит формат вывода."
msgstr ""
"A command outputs data as text, but in some scenarios JSON or CSV is needed. The "
"``--format=json`` flag will switch the output format."
#: ../../root/flags.rst:36
msgid "**Комбинирование опций**"
msgstr ""
msgstr "**Combining Options**"
#: ../../root/flags.rst:37
msgid ""
"Часто нужна комбинация нескольких изменений: подробный вывод, dry-run "
"режим и JSON формат. Несколько флагов решают эту задачу одновременно."
msgstr ""
"Often a combination of several changes is needed: verbose output, dry-run mode, and "
"JSON format. Multiple flags solve this task simultaneously."
#: ../../root/flags.rst:40
msgid "Практическое значение"
msgstr ""
msgstr "Practical Significance"
#: ../../root/flags.rst:42
msgid ""
@@ -125,6 +142,9 @@ msgid ""
"необходимости. Это особенно важно при автоматизации задач в скриптах, где"
" гибкость интерфейса критична."
msgstr ""
"Flags make commands more predictable and controllable. Users can start with simple "
"usage and then add flags as needed. This is especially important when automating "
"tasks in scripts, where interface flexibility is critical."
#: ../../root/flags.rst:44
msgid ""
@@ -132,24 +152,29 @@ msgid ""
"дополнительное поведение достигается без изменения структуры команды, а "
"только через передачу опциональных параметров."
msgstr ""
"Flags also facilitate command integration into various systems, as additional "
"behavior is achieved without changing the command structure, only through passing "
"optional parameters."
#: ../../root/flags.rst:49
msgid "Синтаксис флагов"
msgstr ""
msgstr "Flag Syntax"
#: ../../root/flags.rst:51
msgid "Общий синтаксис выглядит так:"
msgstr ""
msgstr "The general syntax looks like this:"
#: ../../root/flags.rst:57
msgid ""
"Флаг состоит из префикса (``-``, ``--`` или ``---``), имени и, "
"опционально, значения, которое указывается через пробел."
msgstr ""
"A flag consists of a prefix (``-``, ``--``, or ``---``), a name, and optionally a "
"value, which is specified with a space."
#: ../../root/flags.rst:62
msgid "Два типа флагов"
msgstr ""
msgstr "Two Types of Flags"
#: ../../root/flags.rst:64
msgid ""
@@ -157,6 +182,9 @@ msgid ""
"значениями. ``Argenta`` позволяет регистрировать и вводить флаги обоих "
"типов в любой последовательности для одной команды."
msgstr ""
"Flags come in two main types: without values (switches) and with values. "
"``Argenta`` allows registering and entering flags of both types in any sequence "
"for a single command."
#: ../../root/flags.rst:67
msgid ""
@@ -166,6 +194,10 @@ msgid ""
"Подробное описание API для создания флагов находится в разделе :ref:`Flag"
" <root_api_command_flag>`."
msgstr ""
"Validation errors do not throw exceptions. Instead, each :ref:`InputFlag "
"<root_api_command_input_flag>` object has a ``status`` attribute that can be used "
"to determine if validation was successful. A detailed description of the API for "
"creating flags is in the :ref:`Flag <root_api_command_flag>` section."
#: ../../root/flags.rst:69
msgid ""
@@ -173,20 +205,24 @@ msgid ""
" умолчанию любое значение считается корректным. Валидацию можно настроить"
" несколькими способами:"
msgstr ""
"When registering a flag, you can set validation rules for its value. By default, "
"any value is considered valid. Validation can be configured in several ways:"
#: ../../root/flags.rst:74
msgid "Флаги против аргументов"
msgstr ""
msgstr "Flags vs Arguments"
#: ../../root/flags.rst:76
msgid ""
"В контексте Argenta флаги и аргументы относятся к разным уровням "
"взаимодействия с приложением и имеют принципиально разные сферы действия."
msgstr ""
"In the context of Argenta, flags and arguments belong to different levels of "
"interaction with the application and have fundamentally different scopes."
#: ../../root/flags.rst:79
msgid "Определение и назначение"
msgstr ""
msgstr "Definition and Purpose"
#: ../../root/flags.rst:81
msgid ""
@@ -195,6 +231,9 @@ msgid ""
" приложения на протяжении всей его работы, например адрес базы данных, "
"уровень логирования или режим работы."
msgstr ""
"**Arguments** are parameters passed when launching the application once during "
"initialization. They define the global state and configuration of the application "
"throughout its operation, such as database address, logging level, or operation mode."
#: ../../root/flags.rst:83
msgid ""
@@ -202,6 +241,9 @@ msgid ""
"<root_api_orchestrator_argparser>` и :ref:`Arguments "
"<root_api_orchestrator_arguments>`."
msgstr ""
"API and more detailed description in the :ref:`ArgParser "
"<root_api_orchestrator_argparser>` and :ref:`Arguments "
"<root_api_orchestrator_arguments>` sections."
#: ../../root/flags.rst:85
msgid ""
@@ -209,20 +251,23 @@ msgid ""
"интерактивной сессии при вводе каждой новой команды. Они позволяют "
"модифицировать поведение конкретной команды без перезагрузки приложения."
msgstr ""
"**Flags** are command operation parameters available within an interactive session "
"when entering each new command. They allow modifying the behavior of a specific "
"command without restarting the application."
#: ../../root/flags.rst:87
msgid ""
"API и более подробное описание в разделе :ref:`Flag "
"<root_api_command_flag>`."
msgstr ""
msgstr "API and more detailed description in the :ref:`Flag <root_api_command_flag>` section."
#: ../../root/flags.rst:92
msgid "Ключевые различия"
msgstr ""
msgstr "Key Differences"
#: ../../root/flags.rst:94
msgid "**Время жизни и область действия**"
msgstr ""
msgstr "**Lifetime and Scope**"
#: ../../root/flags.rst:95
msgid ""
@@ -230,30 +275,37 @@ msgid ""
" на весь период работы (скоуп **APP**). Флаги наоборот локальны и живут в"
" рамках скоупа **REQUEST**."
msgstr ""
"Arguments are passed once when launching the application and remain in effect for "
"the entire operation period (scope **APP**). Flags, on the contrary, are local and "
"live within the **REQUEST** scope."
#: ../../root/flags.rst:97
msgid "**Частота изменения**"
msgstr ""
msgstr "**Change Frequency**"
#: ../../root/flags.rst:98
msgid ""
"Для изменения аргументов необходимо перезапустить приложение. Флаги можно"
" менять между каждым вводом команды без остановки приложения."
msgstr ""
"To change arguments, the application must be restarted. Flags can be changed "
"between each command input without stopping the application."
#: ../../root/flags.rst:100
msgid "**Уровень конфигурации**"
msgstr ""
msgstr "**Configuration Level**"
#: ../../root/flags.rst:101
msgid ""
"Аргументы управляют глобальной конфигурацией приложения и его окружением."
" Флаги управляют поведением отдельных команд и операций пользователя."
msgstr ""
"Arguments control the global configuration of the application and its environment. "
"Flags control the behavior of individual commands and user operations."
#: ../../root/flags.rst:103
msgid "**Использование**"
msgstr ""
msgstr "**Usage**"
#: ../../root/flags.rst:104
msgid ""
@@ -261,46 +313,48 @@ msgid ""
"работать. Флаги управляют тактикой выполнения команд: как её выполнить, с"
" какими изменениями."
msgstr ""
"Arguments set the initial state of the system: what to connect, how to operate. "
"Flags control the tactics of command execution: how to execute it, with what changes."
#: ../../root/flags.rst:109
msgid "Практические примеры в Argenta"
msgstr ""
msgstr "Practical Examples in Argenta"
#: ../../root/flags.rst:111
msgid "При запуске приложения Argenta передаются аргументы:"
msgstr ""
msgstr "When launching an Argenta application, arguments are passed:"
#: ../../root/flags.rst:113
msgid "Адрес подключения к базе данных"
msgstr ""
msgstr "Database connection address"
#: ../../root/flags.rst:114
msgid "Режим работы (production, development, testing)"
msgstr ""
msgstr "Operation mode (production, development, testing)"
#: ../../root/flags.rst:115
msgid "Уровень логирования"
msgstr ""
msgstr "Logging level"
#: ../../root/flags.rst:116
msgid "Путь к конфигурационным файлам"
msgstr ""
msgstr "Path to configuration files"
#: ../../root/flags.rst:118
msgid "В интерактивной сессии для каждой команды указываются флаги:"
msgstr ""
msgstr "In an interactive session, flags are specified for each command:"
#: ../../root/flags.rst:120
msgid "``deploy --verbose --dry-run`` — для текущей команды развёртывания"
msgstr ""
msgstr "``deploy --verbose --dry-run`` — for the current deployment command"
#: ../../root/flags.rst:121
msgid "``backup --compress --encrypted`` — для команды резервного копирования"
msgstr ""
msgstr "``backup --compress --encrypted`` — for the backup command"
#: ../../root/flags.rst:122
msgid "``test --parallel --coverage`` — для команды тестирования"
msgstr ""
msgstr "``test --parallel --coverage`` — for the testing command"
#: ../../root/flags.rst:124
msgid ""
@@ -308,4 +362,6 @@ msgid ""
"одной сессии приложения, без необходимости перезапуска с новыми "
"аргументами."
msgstr ""
"A single user can execute different commands with different flags in one application "
"session, without needing to restart with new arguments."
@@ -3,7 +3,6 @@
# This file is distributed under the same license as the Argenta package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Argenta \n"
@@ -21,7 +20,7 @@ msgstr ""
#: ../../root/overriding_formatting.rst:4
msgid "Форматирование вывода"
msgstr ""
msgstr "Output Formatting"
#: ../../root/overriding_formatting.rst:6
msgid ""
@@ -30,10 +29,13 @@ msgid ""
"создавать таблицы, подсвечивать синтаксис и многое другое, что улучшает "
"визуальное восприятие информации."
msgstr ""
"By default, ``Argenta`` uses the ``rich`` library for text output with enhanced "
"formatting. It allows applying colors and styles, creating tables, highlighting "
"syntax, and much more, which improves the visual perception of information."
#: ../../root/overriding_formatting.rst:11
msgid "Управление стандартным форматированием"
msgstr ""
msgstr "Managing Standard Formatting"
#: ../../root/overriding_formatting.rst:13
msgid ""
@@ -41,22 +43,28 @@ msgid ""
"``override_system_messages: bool`` (по умолчанию ``False``), который "
"позволяет отключать стандартное форматирование."
msgstr ""
"When creating an ``App`` instance, you can use the ``override_system_messages: "
"bool`` parameter (default ``False``), which allows disabling standard formatting."
#: ../../root/overriding_formatting.rst:15
msgid ""
"Если установить его в ``True``, стилизация текста и ASCII-арт будут "
"отключены, а системные сообщения — выводиться в «сыром» виде."
msgstr ""
"If set to ``True``, text styling and ASCII art will be disabled, and system "
"messages will be output in \"raw\" form."
#: ../../root/overriding_formatting.rst:20
msgid "Приветственное и прощальное сообщения"
msgstr ""
msgstr "Welcome and Farewell Messages"
#: ../../root/overriding_formatting.rst:22
msgid ""
"Приветственное (``initial_message``) и прощальное (``farewell_message``) "
"сообщения по умолчанию выводятся в виде ASCII-графики."
msgstr ""
"Welcome (``initial_message``) and farewell (``farewell_message``) messages are "
"displayed as ASCII art by default."
#: ../../root/overriding_formatting.rst:25
msgid ""
@@ -67,16 +75,23 @@ msgid ""
"``override_system_messages=True`` или использовать только латинские "
"символы."
msgstr ""
"The ``art`` library is designed to work with ASCII characters and **does not "
"support Cyrillic**. This leads to distortion of Russian and other Cyrillic "
"alphabet characters. If your message contains Cyrillic, it is recommended to "
"disable formatting using ``override_system_messages=True`` or use only Latin "
"characters."
#: ../../root/overriding_formatting.rst:30
msgid "Кастомизация вывода"
msgstr ""
msgstr "Output Customization"
#: ../../root/overriding_formatting.rst:32
msgid ""
"Для полной замены логики вывода текста в конструкторе ``App`` "
"предусмотрен параметр ``print_func``."
msgstr ""
"For complete replacement of text output logic, the ``App`` constructor provides "
"the ``print_func`` parameter."
#: ../../root/overriding_formatting.rst:34
msgid ""
@@ -86,6 +101,10 @@ msgid ""
"``rich.console.Console().print``. Вы можете передать сюда свою функцию, "
"чтобы, например, логировать вывод в файл или отправлять его по сети."
msgstr ""
"**print_func**: ``Callable[[str], None]`` This parameter allows passing any "
"callable entity (for example, a function) that will be used to output all system "
"messages. By default, this is ``rich.console.Console().print``. You can pass your "
"own function here to, for example, log output to a file or send it over the network."
#: ../../root/overriding_formatting.rst:38
msgid ""
@@ -94,4 +113,7 @@ msgid ""
"выводиться в сыром виде, в этом случае рекомендуется переопределить "
"стандартное форматирование с помощью ``override_system_messages=True``."
msgstr ""
"When overriding the output function, you should ensure it supports ``rich`` markup, "
"otherwise system messages will be output in raw form. In this case, it is "
"recommended to override standard formatting using ``override_system_messages=True``."
+25 -11
View File
@@ -21,33 +21,37 @@ msgstr ""
#: ../../root/quickstart.rst:4
msgid "Быстрый старт"
msgstr ""
msgstr "Quick Start"
#: ../../root/quickstart.rst:6
msgid ""
"В этом руководстве мы рассмотрим два примера создания CLI-приложения с "
"помощью Argenta:"
msgstr ""
"In this guide, we will look at two examples of creating a CLI application with Argenta:"
#: ../../root/quickstart.rst:8
msgid ""
"**Простой пример**: Минимальное приложение, быстрое знакомство с "
"основными компонентами."
msgstr ""
"**Simple example**: A minimal application, quick introduction to the main components."
#: ../../root/quickstart.rst:9
msgid ""
"**Более сложный пример**: Полнофункциональное приложение «Менеджер задач»"
" с внедрением зависимостей и бизнес-логикой."
msgstr ""
"**More complex example**: A full-featured \"Task Manager\" application with "
"dependency injection and business logic."
#: ../../root/quickstart.rst:12
msgid "Простой пример"
msgstr ""
msgstr "Simple Example"
#: ../../root/quickstart.rst:14 ../../root/quickstart.rst:38
msgid "**Установка**"
msgstr ""
msgstr "**Installation**"
#: ../../root/quickstart.rst:20
msgid ""
@@ -55,10 +59,12 @@ msgid ""
"запуска приложения. Вы можете скопировать этот код, запустить его и сразу"
" увидеть результат."
msgstr ""
"This example demonstrates the absolute minimum required to create and run an "
"application. You can copy this code, run it, and immediately see the result."
#: ../../root/quickstart.rst:26 ../../root/quickstart.rst:76
msgid "**Результат**"
msgstr ""
msgstr "**Result**"
#: ../../root/quickstart.rst:28
msgid "Simple App Example"
@@ -66,7 +72,7 @@ msgstr ""
#: ../../root/quickstart.rst:34
msgid "Более сложный пример: Менеджер задач"
msgstr ""
msgstr "More Complex Example: Task Manager"
#: ../../root/quickstart.rst:36
msgid ""
@@ -74,50 +80,58 @@ msgid ""
"CLI-приложение «Менеджер задач», которое продемонстрирует ключевые "
"возможности Argenta."
msgstr ""
"In this guide, we will create a simple but full-featured CLI application \"Task "
"Manager\" that will demonstrate the key features of Argenta."
#: ../../root/quickstart.rst:44
msgid "**Определение моделей данных и репозитория**"
msgstr ""
msgstr "**Defining Data Models and Repository**"
#: ../../root/quickstart.rst:46
msgid "Сначала определим модели данных для задачи и репозиторий для их хранения."
msgstr ""
msgstr "First, let's define data models for tasks and a repository to store them."
#: ../../root/quickstart.rst:52
msgid "**Создание провайдера для DI**"
msgstr ""
msgstr "**Creating a Provider for DI**"
#: ../../root/quickstart.rst:54
msgid ""
"Чтобы Argenta могла внедрять ``TaskRepository`` в наши обработчики, мы "
"создадим провайдер для ``dishka``."
msgstr ""
"To allow Argenta to inject ``TaskRepository`` into our handlers, we will create a "
"provider for ``dishka``."
#: ../../root/quickstart.rst:60
msgid "**Создание обработчиков команд**"
msgstr ""
msgstr "**Creating Command Handlers**"
#: ../../root/quickstart.rst:62
msgid ""
"Теперь создадим обработчики для команд ``add-task`` и ``list-tasks``. "
"Обратите внимание, как мы используем флаги и внедряем ``TaskRepository``."
msgstr ""
"Now let's create handlers for the ``add-task`` and ``list-tasks`` commands. Notice "
"how we use flags and inject ``TaskRepository``."
#: ../../root/quickstart.rst:68
msgid "**Сборка и запуск приложения**"
msgstr ""
msgstr "**Building and Running the Application**"
#: ../../root/quickstart.rst:70
msgid ""
"Наконец, соберем все вместе: создадим экземпляр ``App``, подключим роутер"
" и провайдер, а затем запустим приложение."
msgstr ""
"Finally, let's put it all together: create an ``App`` instance, connect the router "
"and provider, and then run the application."
#: ../../root/quickstart.rst:78
msgid ""
"Теперь вы можете запустить ``main.py`` и взаимодействовать с вашим новым "
"CLI-приложением."
msgstr ""
msgstr "Now you can run ``main.py`` and interact with your new CLI application."
#: ../../root/quickstart.rst:80
msgid "Task Manager Example"
@@ -3,7 +3,6 @@
# This file is distributed under the same license as the Argenta package.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2025.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: Argenta \n"
@@ -21,7 +20,7 @@ msgstr ""
#: ../../root/redirect_stdout.rst:4
msgid "Переопределение стандартного вывода"
msgstr ""
msgstr "Overriding Standard Output"
#: ../../root/redirect_stdout.rst:6
msgid ""
@@ -30,10 +29,13 @@ msgid ""
"перехвата стандартного потока вывода (``stdout``), что накладывает "
"некоторые особенности."
msgstr ""
"``Argenta`` provides flexible mechanisms for output formatting, including dynamic "
"dividing lines. This is achieved by intercepting the standard output stream "
"(``stdout``), which imposes certain specifics."
#: ../../root/redirect_stdout.rst:11
msgid "Механизм перехвата ``stdout``"
msgstr ""
msgstr "``stdout`` Interception Mechanism"
#: ../../root/redirect_stdout.rst:13
msgid ""
@@ -44,10 +46,15 @@ msgid ""
"создаёт аккуратный интерфейс, где вывод команды «обёрнут» в рамку, "
"подогнанную под его содержимое."
msgstr ""
"By default, ``Argenta`` intercepts all text output to ``stdout`` inside a command "
"handler. This is necessary to implement **dynamic dividers**: the system analyzes "
"the output, finds the longest line, and uses it to draw the top and bottom borders. "
"This approach creates a neat interface where the command output is \"wrapped\" in a "
"frame fitted to its content."
#: ../../root/redirect_stdout.rst:15
msgid "Пример приложения с динамической разделительной линией:"
msgstr ""
msgstr "Example of an application with a dynamic dividing line:"
#: ../../root/redirect_stdout.rst:17
msgid "Example of an application with a dynamic dividing line"
@@ -58,10 +65,12 @@ msgid ""
"Как вы можете заметить разделительная линия ровно той же длины, что и "
"самая длинная строка в выводе."
msgstr ""
"As you can notice, the dividing line is exactly the same length as the longest line "
"in the output."
#: ../../root/redirect_stdout.rst:22
msgid "То же приложение с статической линией:"
msgstr ""
msgstr "The same application with a static line:"
#: ../../root/redirect_stdout.rst:24
msgid "Example of an application with a static dividing line"
@@ -71,11 +80,11 @@ msgstr ""
msgid ""
"В этом примере разделительная линия имеет фиксированную длину (по "
"умолчанию 25 символов)."
msgstr ""
msgstr "In this example, the dividing line has a fixed length (25 characters by default)."
#: ../../root/redirect_stdout.rst:32
msgid "Побочные эффекты перехвата ``stdout``"
msgstr ""
msgstr "Side Effects of ``stdout`` Interception"
#: ../../root/redirect_stdout.rst:34
msgid ""
@@ -83,6 +92,9 @@ msgid ""
"которые последовательно выводят текст в консоль и ожидают ввод от "
"пользователя. Классический пример — стандартная функция ``input()``."
msgstr ""
"A side effect of this mechanism manifests when using functions that sequentially "
"output text to the console and expect user input. A classic example is the standard "
"``input()`` function."
#: ../../root/redirect_stdout.rst:44
msgid ""
@@ -91,46 +103,56 @@ msgid ""
"и отобразится лишь после завершения работы обработчика вместе с остальным"
" выводом. Это может сбить пользователя с толку."
msgstr ""
"With ``stdout`` interception enabled, text (for example, ``\"Enter your name: \"``) "
"**will not be output to the console immediately**. It will go into a buffer and "
"appear only after the handler finishes, along with the rest of the output. This can "
"confuse the user."
#: ../../root/redirect_stdout.rst:49
msgid "Отключение перехвата ``stdout`` с помощью ``disable_redirect_stdout``"
msgstr ""
msgstr "Disabling ``stdout`` Interception with ``disable_redirect_stdout``"
#: ../../root/redirect_stdout.rst:51
msgid ""
"Чтобы решить эту проблему, в конструкторе ``Router`` предусмотрен "
"специальный аргумент:"
msgstr ""
msgstr "To solve this problem, the ``Router`` constructor provides a special argument:"
#: ../../root/redirect_stdout.rst:53
msgid "**disable_redirect_stdout** (``bool``, по умолчанию ``False``)"
msgstr ""
msgstr "**disable_redirect_stdout** (``bool``, default ``False``)"
#: ../../root/redirect_stdout.rst:55
msgid ""
"Если при создании роутера установить ``disable_redirect_stdout=True``, "
"механизм перехвата ``stdout`` будет отключён для всех его обработчиков."
msgstr ""
"If you set ``disable_redirect_stdout=True`` when creating a router, the ``stdout`` "
"interception mechanism will be disabled for all its handlers."
#: ../../root/redirect_stdout.rst:57 ../../root/redirect_stdout.rst:87
msgid "**Пример использования:**"
msgstr ""
msgstr "**Usage example:**"
#: ../../root/redirect_stdout.rst:63
msgid ""
"В этом случае ``input()`` будет работать как обычно, и пользователь сразу"
" увидит приглашение к вводу."
msgstr ""
"In this case, ``input()`` will work as usual, and the user will immediately see the "
"input prompt."
#: ../../root/redirect_stdout.rst:68
msgid "Типы разделительных линий"
msgstr ""
msgstr "Types of Dividing Lines"
#: ../../root/redirect_stdout.rst:70
msgid ""
"``Argenta`` поддерживает два типа разделителей, которые настраиваются при"
" инициализации ``App``:"
msgstr ""
"``Argenta`` supports two types of dividers, which are configured during ``App`` "
"initialization:"
#: ../../root/redirect_stdout.rst:72
msgid "**``DynamicDividingLine()``**"
@@ -141,12 +163,14 @@ msgid ""
"Поведение по умолчанию. Длина линии динамически подстраивается под самый "
"длинный текст в выводе."
msgstr ""
"Default behavior. The line length dynamically adjusts to the longest text in the output."
#: ../../root/redirect_stdout.rst:74
msgid ""
"Требует включённого перехвата ``stdout`` "
"(``disable_redirect_stdout=False`` в роутере)."
msgstr ""
"Requires enabled ``stdout`` interception (``disable_redirect_stdout=False`` in the router)."
#: ../../root/redirect_stdout.rst:76
msgid "**``StaticDividingLine(length: int = 25)``**"
@@ -157,6 +181,8 @@ msgid ""
"Линия имеет фиксированную длину (по умолчанию 25 символов), которую можно"
" задать через аргумент ``length``."
msgstr ""
"The line has a fixed length (25 characters by default), which can be set via the "
"``length`` argument."
#: ../../root/redirect_stdout.rst:78
msgid ""
@@ -164,40 +190,44 @@ msgid ""
"``disable_redirect_stdout=True``, так как без перехвата вывода невозможно"
" определить динамическую длину."
msgstr ""
"Used forcibly for routers with ``disable_redirect_stdout=True``, as it is "
"impossible to determine dynamic length without output interception."
#: ../../root/redirect_stdout.rst:83
msgid "Настройка разделительной линии в ``App``"
msgstr ""
msgstr "Configuring the Dividing Line in ``App``"
#: ../../root/redirect_stdout.rst:85
msgid ""
"Вы можете глобально задать тип разделителя для всего приложения через "
"аргумент ``dividing_line`` в конструкторе ``App``."
msgstr ""
"You can globally set the divider type for the entire application via the "
"``dividing_line`` argument in the ``App`` constructor."
#: ../../root/redirect_stdout.rst:96
msgid "Итоговое поведение"
msgstr ""
msgstr "Resulting Behavior"
#: ../../root/redirect_stdout.rst:102
msgid "``disable_redirect_stdout`` на ``Router``"
msgstr ""
msgstr "``disable_redirect_stdout`` on ``Router``"
#: ../../root/redirect_stdout.rst:103
msgid "Тип линии в ``App``"
msgstr ""
msgstr "Line type in ``App``"
#: ../../root/redirect_stdout.rst:104
msgid "Фактическое поведение"
msgstr ""
msgstr "Actual behavior"
#: ../../root/redirect_stdout.rst:105
msgid "``input()`` работает корректно?"
msgstr ""
msgstr "Does ``input()`` work correctly?"
#: ../../root/redirect_stdout.rst:106 ../../root/redirect_stdout.rst:110
msgid "``False`` (по умолчанию)"
msgstr ""
msgstr "``False`` (default)"
#: ../../root/redirect_stdout.rst:107 ../../root/redirect_stdout.rst:115
msgid "``DynamicDividingLine``"
@@ -205,11 +235,11 @@ msgstr ""
#: ../../root/redirect_stdout.rst:108
msgid "Динамическая линия, длина по содержимому"
msgstr ""
msgstr "Dynamic line, length by content"
#: ../../root/redirect_stdout.rst:109 ../../root/redirect_stdout.rst:113
msgid "Нет"
msgstr ""
msgstr "No"
#: ../../root/redirect_stdout.rst:111 ../../root/redirect_stdout.rst:119
msgid "``StaticDividingLine``"
@@ -217,7 +247,7 @@ msgstr ""
#: ../../root/redirect_stdout.rst:112 ../../root/redirect_stdout.rst:120
msgid "Статическая линия указанной длины"
msgstr ""
msgstr "Static line of specified length"
#: ../../root/redirect_stdout.rst:114 ../../root/redirect_stdout.rst:118
msgid "``True``"
@@ -225,11 +255,11 @@ msgstr ""
#: ../../root/redirect_stdout.rst:116
msgid "**Принудительно статическая линия** (длина по умолч.)"
msgstr ""
msgstr "**Forcibly static line** (default length)"
#: ../../root/redirect_stdout.rst:117 ../../root/redirect_stdout.rst:121
msgid "Да"
msgstr ""
msgstr "Yes"
#: ../../root/redirect_stdout.rst:123
msgid ""
@@ -237,4 +267,7 @@ msgid ""
" отключайте перехват ``stdout`` на уровне роутера. Для всех остальных "
"команд можно оставить поведение по умолчанию."
msgstr ""
"Thus, for interactive commands that require user input, disable ``stdout`` "
"interception at the router level. For all other commands, you can leave the default "
"behavior."
+30 -9
View File
@@ -21,17 +21,19 @@ msgstr ""
#: ../../root/testing.rst:2
msgid "Тестирование"
msgstr ""
msgstr "Testing"
#: ../../root/testing.rst:4
msgid ""
"В этом разделе описаны практики тестирования приложений на основе "
"``Argenta``. Примеры основаны на фактическом публичном API."
msgstr ""
"This section describes testing practices for applications based on ``Argenta``. "
"Examples are based on the actual public API."
#: ../../root/testing.rst:7
msgid "Модульное тестирование обработчиков"
msgstr ""
msgstr "Unit Testing Handlers"
#: ../../root/testing.rst:9
msgid ""
@@ -39,25 +41,29 @@ msgid ""
"чистые функции, не поднимая весь цикл приложения. Рекомендуются "
"``unittest`` или ``pytest``."
msgstr ""
"Handlers in ``Argenta`` are regular functions. They are convenient to test as pure "
"functions without starting the entire application cycle. ``unittest`` or ``pytest`` "
"are recommended."
#: ../../root/testing.rst:11 ../../root/testing.rst:24
#: ../../root/testing.rst:37 ../../root/testing.rst:53
msgid "**Пример использования:**"
msgstr ""
msgstr "**Usage example:**"
#: ../../root/testing.rst:20
msgid "Тестирование с внедрением зависимостей (DI)"
msgstr ""
msgstr "Testing with Dependency Injection (DI)"
#: ../../root/testing.rst:22
msgid ""
"Если обработчику нужны зависимости, используйте ``dishka`` и интеграцию "
"``Argenta``:"
msgstr ""
"If a handler needs dependencies, use ``dishka`` and ``Argenta`` integration:"
#: ../../root/testing.rst:33
msgid "Интеграционное тестирование приложения"
msgstr ""
msgstr "Integration Testing of the Application"
#: ../../root/testing.rst:35
msgid ""
@@ -66,10 +72,13 @@ msgid ""
"ввода. Это даёт близкое к реальности поведение без необходимости "
"симулировать ``stdin``."
msgstr ""
"For higher-level tests, assemble ``App`` and ``Router`` and call handlers through "
"command parsing, bypassing the infinite input loop. This provides behavior close to "
"reality without the need to simulate ``stdin``."
#: ../../root/testing.rst:46
msgid "E2E-тестирование цикла"
msgstr ""
msgstr "E2E Testing of the Loop"
#: ../../root/testing.rst:48
msgid ""
@@ -77,6 +86,9 @@ msgid ""
"передачей строк в ``stdin``. Это тяжелее и обычно не требуется. Если всё "
"же необходимо — пример ниже."
msgstr ""
"Full execution of the ``start_polling`` loop can be covered through a subprocess "
"with passing strings to ``stdin``. This is heavier and usually not required. If "
"still necessary, an example is below."
#: ../../root/testing.rst:51
msgid ""
@@ -85,34 +97,43 @@ msgid ""
"``input`` как аргумент ``side_effects``, иначе тестируемое приложение "
"будет ожидать ввода следующей команды и не сможет корректно завершиться."
msgstr ""
"Be sure to pass the exit command string trigger as the last element in the list "
"that you pass in the context manager when patching ``input`` as the ``side_effects`` "
"argument, otherwise the application under test will wait for the next command input "
"and will not be able to terminate correctly."
#: ../../root/testing.rst:62
msgid "Советы по тестированию"
msgstr ""
msgstr "Testing Tips"
#: ../../root/testing.rst:64
msgid "**Изолируйте тесты**: Каждый тест должен быть независимым от других."
msgstr ""
msgstr "**Isolate tests**: Each test should be independent of others."
#: ../../root/testing.rst:65
msgid ""
"**Моки для внешних интеграций**: БД, HTTP-клиенты и т.п. подменяйте "
"заглушками и провайдерами ``dishka``."
msgstr ""
"**Mocks for external integrations**: Replace databases, HTTP clients, etc. with "
"stubs and ``dishka`` providers."
#: ../../root/testing.rst:66
msgid ""
"**Покрывайте ошибочные сценарии**: Некорректные флаги, неизвестные "
"команды, пустой ввод."
msgstr ""
"**Cover error scenarios**: Incorrect flags, unknown commands, empty input."
#: ../../root/testing.rst:67
msgid ""
"**Минимизируйте зависимость от форматирования**: Сравнивайте ключевые "
"фрагменты вывода, а не весь блок целиком."
msgstr ""
"**Minimize formatting dependency**: Compare key output fragments, not the entire "
"block."
#: ../../root/testing.rst:68
msgid "**Измеряйте покрытие**: Используйте ``pytest-cov``."
msgstr ""
msgstr "**Measure coverage**: Use ``pytest-cov``."
+1 -2
View File
@@ -36,8 +36,7 @@
.. code-block:: python
:linenos:
# Внутри обработчика команды
user_name = input("Введите ваше имя: ")
user_name = input("Enter your name: ")
print(f"Привет, {user_name}!")
.. warning::