mirror of
https://github.com/koloideal/Argenta.git
synced 2026-06-10 18:15:28 +03:00
change dataclass to enum
This commit is contained in:
+75
-78
@@ -1,89 +1,86 @@
|
|||||||
from argenta.app import App
|
|
||||||
from argenta.app.autocompleter import AutoCompleter
|
|
||||||
from argenta.router import Router
|
from argenta.router import Router
|
||||||
from argenta.command import Command
|
from argenta.command import Command
|
||||||
from argenta.orchestrator import Orchestrator
|
|
||||||
from argenta.app.dividing_line import DynamicDividingLine
|
|
||||||
from argenta.response import Response
|
from argenta.response import Response
|
||||||
import platform
|
from argenta.response.status import Status
|
||||||
import psutil
|
from argenta.command.flag import Flag
|
||||||
import os
|
from argenta.command.flags import Flags
|
||||||
import subprocess
|
from argenta.app import App
|
||||||
import socket
|
from argenta.orchestrator import Orchestrator
|
||||||
|
|
||||||
# Маршрутизатор для работы с файлами
|
# Создание маршрутизатора
|
||||||
file_router = Router("Файловые операции")
|
file_router = Router("Операции с файлами")
|
||||||
|
|
||||||
|
# Определение флагов для команды копирования
|
||||||
@file_router.command(Command("list", "Список файлов"))
|
copy_flags = Flags(
|
||||||
def list_files(response: Response):
|
Flag('source', '--'),
|
||||||
files = os.listdir()
|
Flag('destination', '--'),
|
||||||
for file in files:
|
Flag('recursive', '--', False), # Булевый флаг без значения
|
||||||
print(file)
|
Flag('force', '-', False) # Короткий булевый флаг
|
||||||
|
|
||||||
|
|
||||||
@file_router.command(Command("size", "Размер файла"))
|
|
||||||
def file_size(response: Response):
|
|
||||||
file_name = input("Введите имя файла: ")
|
|
||||||
if os.path.exists(file_name):
|
|
||||||
size = os.path.getsize(file_name)
|
|
||||||
print(f"Размер файла {file_name}: {size} байт")
|
|
||||||
else:
|
|
||||||
print(f"Файл {file_name} не найден")
|
|
||||||
|
|
||||||
|
|
||||||
# Маршрутизатор для системных операций
|
|
||||||
system_router = Router("Системные операции")
|
|
||||||
|
|
||||||
|
|
||||||
@system_router.command(Command("info", "Информация о системе"))
|
|
||||||
def system_info(response: Response):
|
|
||||||
print(f"Система: {platform.system()}")
|
|
||||||
print(f"Версия: {platform.version()}")
|
|
||||||
print(f"Архитектура: {platform.architecture()}")
|
|
||||||
print(f"Процессор: {platform.processor()}")
|
|
||||||
|
|
||||||
|
|
||||||
@system_router.command(Command("memory", "Информация о памяти"))
|
|
||||||
def memory_info(response: Response):
|
|
||||||
memory = psutil.virtual_memory()
|
|
||||||
print(f"Всего памяти: {memory.total / (1024**3):.2f} ГБ")
|
|
||||||
print(f"Доступно: {memory.available / (1024**3):.2f} ГБ")
|
|
||||||
print(f"Использовано: {memory.used / (1024**3):.2f} ГБ ({memory.percent}%)")
|
|
||||||
|
|
||||||
|
|
||||||
# Маршрутизатор для сетевых операций
|
|
||||||
network_router = Router("Сетевые операции")
|
|
||||||
|
|
||||||
|
|
||||||
@network_router.command(Command("ping", "Проверка доступности хоста"))
|
|
||||||
def ping_host(response: Response):
|
|
||||||
host = input("Введите имя хоста: ")
|
|
||||||
print(f"Пингую {host}...")
|
|
||||||
subprocess.run(["ping", "-c", "4", host])
|
|
||||||
|
|
||||||
|
|
||||||
@network_router.command(Command("ip", "Показать IP-адреса"))
|
|
||||||
def show_ip(response: Response):
|
|
||||||
hostname = socket.gethostname()
|
|
||||||
print(f"Имя хоста: {hostname}")
|
|
||||||
print(f"IP-адрес: {socket.gethostbyname(hostname)}")
|
|
||||||
|
|
||||||
|
|
||||||
# Создание приложения и регистрация маршрутизаторов
|
|
||||||
app = App(
|
|
||||||
prompt="System> ",
|
|
||||||
initial_message="Pingator",
|
|
||||||
dividing_line=DynamicDividingLine("*"),
|
|
||||||
autocompleter=AutoCompleter(".hist", "e"),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Добавляем все маршрутизаторы
|
# Регистрация команды копирования
|
||||||
app.include_routers(file_router, system_router, network_router)
|
@file_router.command(Command(
|
||||||
|
trigger="copy",
|
||||||
|
description="Копирование файлов",
|
||||||
|
flags=copy_flags,
|
||||||
|
aliases=["cp"]
|
||||||
|
))
|
||||||
|
def copy_files(response: Response):
|
||||||
|
# Получаем значения корректных флагов
|
||||||
|
source = None
|
||||||
|
destination = None
|
||||||
|
recursive = False
|
||||||
|
force = False
|
||||||
|
|
||||||
# Добавляем сообщение при запуске
|
for flag in response.valid_flags:
|
||||||
app.add_message_on_startup("Для просмотра доступных команд нажмите Enter")
|
if flag.get_name() == "source":
|
||||||
|
source = flag.get_value()
|
||||||
|
elif flag.get_name() == "destination":
|
||||||
|
destination = flag.get_value()
|
||||||
|
elif flag.get_name() == "recursive":
|
||||||
|
recursive = True
|
||||||
|
elif flag.get_name() == "force":
|
||||||
|
force = True
|
||||||
|
|
||||||
# Запускаем приложение
|
# Проверка обязательных параметров
|
||||||
|
if not source or not destination:
|
||||||
|
print("Ошибка: необходимо указать источник и назначение")
|
||||||
|
return
|
||||||
|
|
||||||
|
print(f"Копирование из {source} в {destination}")
|
||||||
|
if recursive:
|
||||||
|
print("Рекурсивное копирование включено")
|
||||||
|
if force:
|
||||||
|
print("Принудительное копирование включено")
|
||||||
|
|
||||||
|
# Обработка неопределенных флагов
|
||||||
|
if response.undefined_flags:
|
||||||
|
print("\nПредупреждение: обнаружены незарегистрированные флаги:")
|
||||||
|
for flag in response.undefined_flags:
|
||||||
|
print(f" - {flag.get_name()}" +
|
||||||
|
(f" = {flag.get_value()}" if flag.get_value() else ""))
|
||||||
|
|
||||||
|
# Обработка флагов с некорректными значениями
|
||||||
|
if response.invalid_value_flags:
|
||||||
|
print("\nПредупреждение: обнаружены флаги с некорректными значениями:")
|
||||||
|
for flag in response.invalid_value_flags:
|
||||||
|
print(f" - {flag.get_name()} = {flag.get_value()}")
|
||||||
|
|
||||||
|
# Принятие решения на основе статуса
|
||||||
|
if response.status != Status.ALL_FLAGS_VALID:
|
||||||
|
print("\nВыполнение с предупреждениями из-за проблем с флагами.")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
app = App()
|
||||||
|
app.include_router(file_router)
|
||||||
orchestrator = Orchestrator()
|
orchestrator = Orchestrator()
|
||||||
|
|
||||||
orchestrator.start_polling(app)
|
orchestrator.start_polling(app)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
from dataclasses import dataclass
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
class PredefinedMessages(Enum):
|
||||||
class PredefinedMessages:
|
|
||||||
"""
|
"""
|
||||||
Public. A dataclass with predetermined messages for quick use
|
Public. A dataclass with predetermined messages for quick use
|
||||||
"""
|
"""
|
||||||
|
|
||||||
USAGE = "[b dim]Usage[/b dim]: [i]<command> <[green]flags[/green]>[/i]"
|
USAGE = "[b dim]Usage[/b dim]: [i]<command> <[green]flags[/green]>[/i]"
|
||||||
HELP = "[b dim]Help[/b dim]: [i]<command>[/i] [b red]--help[/b red]"
|
HELP = "[b dim]Help[/b dim]: [i]<command>[/i] [b red]--help[/b red]"
|
||||||
AUTOCOMPLETE = "[b dim]Autocomplete[/b dim]: [i]<part>[/i] [bold]<tab>"
|
AUTOCOMPLETE = "[b dim]Autocomplete[/b dim]: [i]<part>[/i] [bold]<tab>"
|
||||||
|
|||||||
Reference in New Issue
Block a user