Skip to content

Commit

Permalink
Meta highlighter + Add loaders in linfo/list + Main color changes (#269)
Browse files Browse the repository at this point in the history
  • Loading branch information
Skazza94 committed Jan 31, 2024
1 parent 5b8f42b commit 373403a
Show file tree
Hide file tree
Showing 8 changed files with 100 additions and 52 deletions.
18 changes: 13 additions & 5 deletions src/Kathara/cli/command/CheckCommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,18 @@ def run(self, current_path: str, argv: List[str]) -> None:
self.parse_args(argv)

self.console.print(create_panel("System Check", style="blue bold", justify="center"))
self.console.print(f"Current Manager is:\t\t[cyan bold]{Kathara.get_instance().get_formatted_manager_name()}")
self.console.print(f"Manager version is:\t\t[cyan bold]{Kathara.get_instance().get_release_version()}")
self.console.print("Python version is:\t\t[cyan bold]%s" % sys.version.replace("\n", "- "))
self.console.print(f"Kathara version is:\t\t[cyan bold]{version.CURRENT_VERSION}")
self.console.print(
f"Current Manager is:\t\t[bold dark_orange3]{Kathara.get_instance().get_formatted_manager_name()}"
)
self.console.print(
f"Manager version is:\t\t[bold dark_orange3]{Kathara.get_instance().get_release_version()}"
)
self.console.print(
"Python version is:\t\t[bold dark_orange3]%s" % sys.version.replace("\n", "- ")
)
self.console.print(
f"Kathara version is:\t\t[bold dark_orange3]{version.CURRENT_VERSION}"
)

def linux_platform_info():
info = os.uname()
Expand All @@ -48,7 +56,7 @@ def linux_platform_info():
platform_info = utils.exec_by_platform(
linux_platform_info, lambda: platform.platform(), lambda: platform.platform()
)
self.console.print(f"Operating System version is:\t[cyan bold]{str(platform_info)}")
self.console.print(f"Operating System version is:\t[bold dark_orange3]{str(platform_info)}")

with self.console.status(
f"Trying to run container with `{Setting.get_instance().image}` image...",
Expand Down
5 changes: 3 additions & 2 deletions src/Kathara/cli/command/ConnectCommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,5 +72,6 @@ def run(self, current_path: str, argv: List[str]) -> None:

logging.debug(f"Executing `connect` command with hash `{lab.hash}`...")

Kathara.get_instance().connect_tty(machine_name=args['machine_name'], lab_hash=lab.hash, shell=args['shell'],
logs=args['logs'])
Kathara.get_instance().connect_tty(
machine_name=args['machine_name'], lab_hash=lab.hash, shell=args['shell'], logs=args['logs']
)
47 changes: 30 additions & 17 deletions src/Kathara/cli/command/LinfoCommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from rich.live import Live

from ..ui.utils import create_panel
from ..ui.utils import create_panel, LabMetaHighlighter
from ..ui.utils import create_table
from ... import utils
from ...foundation.cli.command.Command import Command
Expand Down Expand Up @@ -84,31 +84,37 @@ def run(self, current_path: str, argv: List[str]) -> None:
self._get_conf_info(lab, machine_name=args['name'])
return

if args['name']:
machine_stats = next(Kathara.get_instance().get_machine_stats(args['name'], lab.hash))
message = str(machine_stats) if machine_stats else f"Device `{args['name']}` Not Found."
style = None if machine_stats else "red bold"
with self.console.status(
f"Loading...",
spinner="dots"
) as _:
if args['name']:
machine_stats = next(Kathara.get_instance().get_machine_stats(args['name'], lab.hash))
message = str(machine_stats) if machine_stats else f"Device `{args['name']}` Not Found."
style = None if machine_stats else "red bold"

self.console.print(create_panel(message, title=f"{args['name']} Information", style=style))
else:
machines_stats = Kathara.get_instance().get_machines_stats(lab.hash)
self.console.print(create_table(machines_stats))
self.console.print(create_panel(message, title=f"{args['name']} Information", style=style))
else:
machines_stats = Kathara.get_instance().get_machines_stats(lab.hash)
self.console.print(create_table(machines_stats))

@staticmethod
def _get_machine_live_info(lab: Lab, machine_name: str) -> None:
with Live(None, refresh_per_second=1, screen=True) as live:
def _get_machine_live_info(self, lab: Lab, machine_name: str) -> None:
with Live(None, refresh_per_second=12.5, screen=True) as live:
live.update(self.console.status(f"Loading...", spinner="dots"))
live.refresh_per_second = 1
while True:
machine_stats = next(Kathara.get_instance().get_machine_stats(machine_name, lab.hash))
message = str(machine_stats) if machine_stats else f"Device `{machine_name}` Not Found."
style = None if machine_stats else "red bold"

live.update(create_panel(message, title=f"{machine_name} Information", style=style))

@staticmethod
def _get_lab_live_info(lab: Lab) -> None:
def _get_lab_live_info(self, lab: Lab) -> None:
machines_stats = Kathara.get_instance().get_machines_stats(lab.hash)

with Live(None, refresh_per_second=1, screen=True) as live:
with Live(None, refresh_per_second=12.5, screen=True) as live:
live.update(self.console.status(f"Loading...", spinner="dots"))
live.refresh_per_second = 1
while True:
table = create_table(machines_stats)
if not table:
Expand All @@ -128,14 +134,21 @@ def _get_conf_info(self, lab: Lab, machine_name: str = None) -> None:

lab_meta_information = str(lab)
if lab_meta_information:
self.console.print(create_panel(lab_meta_information, title="Network Scenario Information"))
meta_highlighter = LabMetaHighlighter()
self.console.print(
create_panel(
meta_highlighter(lab_meta_information),
title="Network Scenario Information",
)
)

n_machines = len(lab.machines)
n_links = len(lab.links) if BRIDGE_LINK_NAME not in lab.links else len(lab.links) - 1

self.console.print(
create_panel(
f"There are {n_machines} devices.\nThere are {n_links} collision domains.",
f"There are [bold green]{n_machines}[/bold green] devices.\n"
f"There are [bold green]{n_links}[/bold green] collision domains.",
title="Topology Information"
)
)
20 changes: 13 additions & 7 deletions src/Kathara/cli/command/ListCommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,20 @@ def run(self, current_path: str, argv: List[str]) -> None:
if args['watch']:
self._get_live_info(machine_name=args['name'], all_users=all_users)
else:
machines_stats = Kathara.get_instance().get_machines_stats(machine_name=args['name'], all_users=all_users)
self.console.print(create_table(machines_stats))

@staticmethod
def _get_live_info(machine_name: Optional[str], all_users: bool) -> None:
with self.console.status(
f"Loading...",
spinner="dots"
) as _:
machines_stats = Kathara.get_instance().get_machines_stats(
machine_name=args['name'], all_users=all_users
)
self.console.print(create_table(machines_stats))

def _get_live_info(self, machine_name: Optional[str], all_users: bool) -> None:
machines_stats = Kathara.get_instance().get_machines_stats(machine_name=machine_name, all_users=all_users)

with Live(None, refresh_per_second=1, screen=True) as live:
with Live(None, refresh_per_second=12.5, screen=True) as live:
live.update(self.console.status(f"Loading...", spinner="dots"))
live.refresh_per_second = 1
while True:
table = create_table(machines_stats)
if not table:
Expand Down
5 changes: 3 additions & 2 deletions src/Kathara/cli/command/LstartCommand.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import sys
from typing import List

from ..ui.utils import create_panel
from ..ui.utils import create_panel, LabMetaHighlighter
from ..ui.utils import create_table
from ... import utils
from ...exceptions import PrivilegeError, EmptyLabError
Expand Down Expand Up @@ -169,7 +169,8 @@ def run(self, current_path: str, argv: List[str]) -> Lab:

lab_meta_information = str(lab)
if lab_meta_information:
self.console.print(create_panel(lab_meta_information))
meta_highlighter = LabMetaHighlighter()
self.console.print(create_panel(meta_highlighter(lab_meta_information)))

if len(lab.machines) <= 0:
raise EmptyLabError()
Expand Down
24 changes: 19 additions & 5 deletions src/Kathara/cli/ui/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
import subprocess
import sys
from datetime import datetime
from typing import Any, Dict, Generator, Optional
from typing import Any, Dict, Generator, Optional, Union
from typing import Callable

from rich import box
from rich.console import RenderableType, Group
from rich.highlighter import RegexHighlighter
from rich.panel import Panel
from rich.prompt import Confirm
from rich.table import Table
Expand All @@ -22,6 +23,19 @@
FORBIDDEN_TABLE_COLUMNS = ["container_name"]


class LabMetaHighlighter(RegexHighlighter):
"""Highlights metadata of the network scenario."""
base_style = "kathara."
highlights = [
re.compile(r"(?P<lab_name>^Name: )", re.MULTILINE),
re.compile(r"(?P<lab_description>^Description: )", re.MULTILINE),
re.compile(r"(?P<lab_version>^Version: )", re.MULTILINE),
re.compile(r"(?P<lab_author>^Author\(s\): )", re.MULTILINE),
re.compile(r"(?P<lab_email>^Email: )", re.MULTILINE),
re.compile(r"(?P<lab_web>^Website: )", re.MULTILINE),
]


def confirmation_prompt(prompt_string: str, callback_yes: Callable, callback_no: Callable) -> Any:
answer = Confirm.ask(prompt_string)
if not answer:
Expand All @@ -30,13 +44,13 @@ def confirmation_prompt(prompt_string: str, callback_yes: Callable, callback_no:
return callback_yes()


def create_panel(message: str = "", **kwargs) -> Panel:
def create_panel(message: Union[str, Text], **kwargs) -> Panel:
return Panel(
Text(
Text.from_markup(
message,
style=kwargs['style'] if 'style' in kwargs else "none",
justify=kwargs['justify'] if 'justify' in kwargs else None,
),
) if isinstance(message, str) else message,
title=kwargs['title'] if 'title' in kwargs else None,
title_align="center",
box=kwargs['box'] if 'box' in kwargs else box.SQUARE,
Expand Down Expand Up @@ -64,7 +78,7 @@ def create_table(streams: Generator[Dict[str, IMachineStats], None, None]) -> Op

if not table.columns:
for col in map(lambda x: x.replace('_', ' ').upper(), row_data.keys()):
table.add_column(col, header_style="blue")
table.add_column(col, header_style="dark_orange3")

table.add_row(*map(lambda x: str(x), row_data.values()))

Expand Down
12 changes: 11 additions & 1 deletion src/Kathara/foundation/cli/command/Command.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from typing import List, Dict, Any

from rich.console import Console
from rich.theme import Theme

from ..CliArgs import CliArgs

Expand All @@ -10,7 +11,16 @@ class Command(ABC):
__slots__ = ['parser', 'console']

def __init__(self) -> None:
self.console: Console = Console()
self.console: Console = Console(
theme=Theme({
"kathara.lab_name": "bold dark_orange3",
"kathara.lab_description": "bold dark_orange3",
"kathara.lab_version": "bold dark_orange3",
"kathara.lab_author": "bold dark_orange3",
"kathara.lab_email": "bold dark_orange3",
"kathara.lab_web": "bold dark_orange3",
})
)

@abstractmethod
def run(self, current_path: str, argv: List[str]) -> Any:
Expand Down
21 changes: 8 additions & 13 deletions src/Kathara/model/Lab.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,24 +434,19 @@ def __repr__(self) -> str:
return "Lab(%s, %s, %s, %s)" % (self.fs, self.hash, self.machines, self.links)

def __str__(self) -> str:
lab_info = ""
lab_info = []

if self._name:
lab_info += "Name: %s\n" % self._name

lab_info.append(f"Name: {self._name}")
if self.description:
lab_info += "Description: %s\n" % self.description

lab_info.append(f"Description: {self.description}")
if self.version:
lab_info += "Version: %s\n" % self.version

lab_info.append(f"Version: {self.version}")
if self.author:
lab_info += "Author(s): %s\n" % self.author

lab_info.append(f"Author(s): {self.author}")
if self.email:
lab_info += "Email: %s\n" % self.email

lab_info.append(f"Email: {self.email}")
if self.web:
lab_info += "Website: %s\n" % self.web
lab_info.append(f"Website: {self.web}")

return lab_info[0:-1] # Remove trailing new line
return "\n".join(lab_info)

0 comments on commit 373403a

Please sign in to comment.