Update documentation and code snippets

This commit is contained in:
2025-12-02 22:26:30 +03:00
parent eae8cdbb58
commit e6645730f0
8 changed files with 37 additions and 37 deletions
+6 -5
View File
@@ -6,6 +6,7 @@ app = App(
prompt=">> ", prompt=">> ",
initial_message="Simple App", initial_message="Simple App",
farewell_message="Goodbye!", farewell_message="Goodbye!",
repeat_command_groups_printing=False
) )
orchestrator = Orchestrator() orchestrator = Orchestrator()
@@ -14,11 +15,11 @@ main_router = Router(title="Main commands")
# 3. Define command and its handler # 3. Define command and its handler
@main_router.command( @main_router.command(Command(
Command( "hello",
"hello", description="Prints greeting message", flags=Flag("name") description="Prints greeting message",
) flags=Flag("name")
) ))
def hello_handler(response: Response): def hello_handler(response: Response):
"""This handler will be called for 'hello' command.""" """This handler will be called for 'hello' command."""
name = response.input_flags.get_flag_by_name("name") name = response.input_flags.get_flag_by_name("name")
@@ -1,7 +1,7 @@
from typing import cast from typing import cast
from argenta import Command, Response, Router from argenta import Command, Response, Router
from argenta.command.flag import ValidationStatus, Flag, Flags from argenta.command.flag import Flag, Flags, ValidationStatus
from argenta.di import FromDishka from argenta.di import FromDishka
from .repository import Priority, Task, TaskRepository from .repository import Priority, Task, TaskRepository
@@ -9,26 +9,25 @@ from .repository import Priority, Task, TaskRepository
router = Router(title="Task Manager") router = Router(title="Task Manager")
@router.command( @router.command(Command(
Command(
"add-task", "add-task",
description="Add a new task", description="Add a new task",
flags=Flags( flags=Flags([
[
Flag("description"), Flag("description"),
Flag("priority", possible_values=["low", "medium", "high"]), Flag("priority", possible_values=["low", "medium", "high"]),
] ]),
), ))
)
)
def add_task(response: Response, repo: FromDishka[TaskRepository]): def add_task(response: Response, repo: FromDishka[TaskRepository]):
description_flag = response.input_flags.get_flag_by_name("description") description_flag = response.input_flags.get_flag_by_name("description")
if not description_flag or not description_flag.status == ValidationStatus.VALID: if not description_flag or not description_flag.status == ValidationStatus.VALID:
print("Error: --description flag is required.") print("Error: --description flag is required.")
return return
task_description = description_flag.input_value or "" task_description = description_flag.input_value or ""
priority_flag = response.input_flags.get_flag_by_name("priority") priority_flag = response.input_flags.get_flag_by_name("priority")
if priority_flag and priority_flag.status == ValidationStatus.VALID: if priority_flag and priority_flag.status == ValidationStatus.VALID:
priority_value = priority_flag.input_value priority_value = priority_flag.input_value
else: else:
@@ -38,12 +37,14 @@ def add_task(response: Response, repo: FromDishka[TaskRepository]):
task = Task(description=task_description, priority=priority) task = Task(description=task_description, priority=priority)
repo.add_task(task) repo.add_task(task)
print(f"Added task: '{task.description}' with priority '{task.priority}'") print(f"Added task: '{task.description}' with priority '{task.priority}'")
@router.command(Command("list-tasks", description="List all tasks")) @router.command(Command("list-tasks", description="List all tasks"))
def list_tasks(response: Response, repo: FromDishka[TaskRepository]): def list_tasks(response: Response, repo: FromDishka[TaskRepository]):
tasks = repo.get_all_tasks() tasks = repo.get_all_tasks()
if not tasks: if not tasks:
print("No tasks found.") print("No tasks found.")
return return
+2 -2
View File
@@ -25,7 +25,7 @@
**Результат** **Результат**
.. image:: https://i.ibb.co/JwK9Vv4j/2025-11-03-135118.png .. image:: https://i.ibb.co/35q24Bh8/image.png
:alt: Simple App Example :alt: Simple App Example
----- -----
@@ -43,7 +43,7 @@
2. **Определение моделей данных и репозитория** 2. **Определение моделей данных и репозитория**
Сначала определим модели данных для задачи и репозиторий для их хранения. Это будет наша "бизнес-логика". Сначала определим модели данных для задачи и репозиторий для их хранения.
.. literalinclude:: ../code_snippets/quickstart/task_manager/repository.py .. literalinclude:: ../code_snippets/quickstart/task_manager/repository.py
:language: python :language: python
+9 -9
View File
@@ -1,11 +1,11 @@
from argenta.orchestrator.argparser import ArgSpace, BooleanArgument, ValueArgument from argenta import Router, Command
from argenta.orchestrator.argparser.arguments import InputArgument
argspace = ArgSpace([ router = Router()
InputArgument(name="arg1", value="val1", founder_class=ValueArgument), @router.command(Command('some', aliases=['test', 'case']))
InputArgument(name="arg2", value=True, founder_class=BooleanArgument), def handler(response): # pyright: ignore[reportUnusedFunction]
InputArgument(name="arg3", value="val3", founder_class=ValueArgument), pass
]) @router.command(Command('ext', aliases=['more', 'foo']))
def handler2(response): # pyright: ignore[reportUnusedFunction]
pass
print(argspace._name_object_paired_args) print(router.aliases)
print(argspace.get_by_type(ValueArgument))
+4 -4
View File
@@ -44,13 +44,13 @@ class Flag:
if self.possible_values == PossibleValues.NEITHER: if self.possible_values == PossibleValues.NEITHER:
return input_flag_value is None return input_flag_value is None
if self.possible_values == PossibleValues.ALL:
return input_flag_value is not None
if isinstance(self.possible_values, Pattern): if isinstance(self.possible_values, Pattern):
return isinstance(input_flag_value, str) and bool(self.possible_values.match(input_flag_value)) return isinstance(input_flag_value, str) and bool(self.possible_values.match(input_flag_value))
if isinstance(self.possible_values, list): return input_flag_value in self.possible_values
return input_flag_value in self.possible_values
return True
@property @property
def string_entity(self) -> str: def string_entity(self) -> str:
+1 -1
View File
@@ -39,7 +39,7 @@ class Command:
self.registered_flags: Flags = flags if isinstance(flags, Flags) else Flags([flags]) self.registered_flags: Flags = flags if isinstance(flags, Flags) else Flags([flags])
self.trigger: str = trigger self.trigger: str = trigger
self.description: str = description self.description: str = description
self.aliases: list[str] = [] self.aliases: list[str] = aliases
def validate_input_flag(self, flag: InputFlag) -> ValidationStatus: def validate_input_flag(self, flag: InputFlag) -> ValidationStatus:
""" """
+3 -4
View File
@@ -26,13 +26,13 @@ class TestInputCommand(unittest.TestCase):
with self.assertRaises(EmptyInputCommandException): with self.assertRaises(EmptyInputCommandException):
InputCommand.parse('') InputCommand.parse('')
def test_validate_valid_input_flag1(self): def test_validate_invalid_input_flag1(self):
command = Command('some', flags=Flag('test')) command = Command('some', flags=Flag('test'))
self.assertEqual(command.validate_input_flag(InputFlag('test', input_value=None, status=None)), ValidationStatus.VALID) self.assertEqual(command.validate_input_flag(InputFlag('test', input_value=None, status=None)), ValidationStatus.INVALID)
def test_validate_valid_input_flag2(self): def test_validate_valid_input_flag2(self):
command = Command('some', flags=Flags([Flag('test'), Flag('more')])) command = Command('some', flags=Flags([Flag('test'), Flag('more')]))
self.assertEqual(command.validate_input_flag(InputFlag('more', input_value=None, status=None)), ValidationStatus.VALID) self.assertEqual(command.validate_input_flag(InputFlag('more', input_value='random-value', status=None)), ValidationStatus.VALID)
def test_validate_undefined_input_flag1(self): def test_validate_undefined_input_flag1(self):
command = Command('some', flags=Flag('test')) command = Command('some', flags=Flag('test'))
@@ -61,4 +61,3 @@ class TestInputCommand(unittest.TestCase):
def test_isinstance_parse_correct_raw_command(self): def test_isinstance_parse_correct_raw_command(self):
cmd = InputCommand.parse('ssh --host 192.168.0.3') cmd = InputCommand.parse('ssh --host 192.168.0.3')
self.assertIsInstance(cmd, InputCommand) self.assertIsInstance(cmd, InputCommand)
+1 -2
View File
@@ -7,8 +7,7 @@ from argenta.command.flag.flags import Flags, InputFlags
from argenta.command.flag.models import PossibleValues, ValidationStatus from argenta.command.flag.models import PossibleValues, ValidationStatus
from argenta.response.entity import Response from argenta.response.entity import Response
from argenta.router import Router from argenta.router import Router
from argenta.router.entity import ( # pyright: ignore[reportPrivateUsage] from argenta.router.entity import _structuring_input_flags, _validate_command, _validate_func_args # pyright: ignore[reportPrivateUsage]
_structuring_input_flags, _validate_command, _validate_func_args)
from argenta.router.exceptions import (RepeatedFlagNameException, from argenta.router.exceptions import (RepeatedFlagNameException,
RequiredArgumentNotPassedException, RequiredArgumentNotPassedException,
TriggerContainSpacesException) TriggerContainSpacesException)