Skip to content

Commit

Permalink
Fix table layout (tests didn't catch this)
Browse files Browse the repository at this point in the history
  • Loading branch information
terjekv committed Nov 12, 2023
1 parent cfde9ae commit 232b9bc
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 39 deletions.
4 changes: 2 additions & 2 deletions mreg_cli/bacnet.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from .history import history
from .host import host
from .log import cli_error, cli_info
from .util import delete, format_table, get, get_list, host_info_by_name, post
from .util import add_formatted_table_for_output, delete, get, get_list, host_info_by_name, post


def bacnetid_add(args) -> None:
Expand Down Expand Up @@ -74,7 +74,7 @@ def bacnetid_list(args) -> None:
if maxval > 4194302:
cli_error("The maximum ID value is 4194302.")
r = get_list("/api/v1/bacnet/ids/", {"id__range": "{},{}".format(minval, maxval)})
format_table(("ID", "Hostname"), ("id", "hostname"), r)
add_formatted_table_for_output(("ID", "Hostname"), ("id", "hostname"), r)


host.add_command(
Expand Down
6 changes: 3 additions & 3 deletions mreg_cli/label.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from .history import history
from .log import cli_info, cli_warning
from .outputmanager import OutputManager
from .util import delete, format_table, get, get_list, patch, post
from .util import add_formatted_table_for_output, delete, get, get_list, patch, post

label = cli.add_command(
prog="label",
Expand Down Expand Up @@ -38,7 +38,7 @@ def label_list(args) -> None:
if not labels:
cli_info("No labels", True)
return
format_table(("Name", "Description"), ("name", "description"), labels)
add_formatted_table_for_output(("Name", "Description"), ("name", "description"), labels)


label.add_command(prog="list", description="List labels", callback=label_list, flags=[])
Expand Down Expand Up @@ -83,7 +83,7 @@ def label_info(args) -> None:
permlist = get_list("/api/v1/permissions/netgroupregex/", params={"labels__name": args.name})
manager.add_line("Permissions with this label:")
if permlist:
format_table(
add_formatted_table_for_output(
("IP range", "Group", "Reg.exp."),
("range", "group", "regex"),
permlist,
Expand Down
4 changes: 2 additions & 2 deletions mreg_cli/permission.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
from .history import history
from .log import cli_info, cli_warning
from .util import (
add_formatted_table_for_output,
convert_wildcard_to_regex,
delete,
format_table,
get,
get_list,
is_valid_network,
Expand Down Expand Up @@ -77,7 +77,7 @@ def _supernet_of(a, b):

headers = ("Range", "Group", "Regex", "Labels")
keys = ("range", "group", "regex", "labels")
format_table(headers, keys, data)
add_formatted_table_for_output(headers, keys, data)


permission.add_command(
Expand Down
6 changes: 4 additions & 2 deletions mreg_cli/policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
from .log import cli_error, cli_info, cli_warning
from .outputmanager import OutputManager
from .util import (
add_formatted_table_for_output,
convert_wildcard_to_regex,
delete,
format_table,
get,
get_list,
host_info_by_name,
Expand Down Expand Up @@ -393,7 +393,9 @@ def list_roles(args) -> None:
labels.append(labelnames[j])
i["labels"] = ", ".join(labels)
rows.append(i)
format_table(("Role", "Description", "Labels"), ("name", "description", "labels"), rows)
add_formatted_table_for_output(
("Role", "Description", "Labels"), ("name", "description", "labels"), rows
)


policy.add_command(
Expand Down
44 changes: 14 additions & 30 deletions mreg_cli/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
overload,
)

from .outputmanager import OutputManager

if TYPE_CHECKING:
from typing_extensions import Literal

Expand Down Expand Up @@ -70,9 +72,7 @@ def host_exists(name: str) -> bool:

# Response data sanity checks
if len(hosts) > 1:
cli_error(
'host exist check received more than one exact match for "{}"'.format(name)
)
cli_error('host exist check received more than one exact match for "{}"'.format(name))
if len(hosts) == 0:
return False
if hosts[0]["name"] != name:
Expand Down Expand Up @@ -176,9 +176,7 @@ def first_unused_ip_from_network(network: dict) -> str:
"""
unused = get_network_first_unused(network["network"])
if not unused:
cli_warning(
"No free addresses remaining on network {}".format(network["network"])
)
cli_warning("No free addresses remaining on network {}".format(network["network"]))
return unused


Expand Down Expand Up @@ -323,9 +321,7 @@ def _request_wrapper(
rec = recorder.Recorder()

if use_json:
result = getattr(session, operation_type)(
url, json=params, timeout=HTTP_TIMEOUT
)
result = getattr(session, operation_type)(url, json=params, timeout=HTTP_TIMEOUT)
else:
result = getattr(session, operation_type)(
url, params=params, data=data, timeout=HTTP_TIMEOUT
Expand All @@ -346,9 +342,7 @@ def _request_wrapper(


@overload
def get(
path: str, params: Dict[str, str], ok404: "Literal[True]"
) -> Optional["ResponseLike"]:
def get(path: str, params: Dict[str, str], ok404: "Literal[True]") -> Optional["ResponseLike"]:
...


Expand All @@ -358,9 +352,7 @@ def get(path: str, params: Dict[str, str], ok404: "Literal[False]") -> "Response


@overload
def get(
path: str, params: Dict[str, str] = ..., *, ok404: bool
) -> Optional["ResponseLike"]:
def get(path: str, params: Dict[str, str] = ..., *, ok404: bool) -> Optional["ResponseLike"]:
...


Expand All @@ -369,18 +361,14 @@ def get(path: str, params: Dict[str, str] = ...) -> "ResponseLike":
...


def get(
path: str, params: Dict[str, str] = None, ok404: bool = False
) -> Optional["ResponseLike"]:
def get(path: str, params: Dict[str, str] = None, ok404: bool = False) -> Optional["ResponseLike"]:
"""Uses requests to make a get request."""
if params is None:
params = {}
return _request_wrapper("get", path, params=params, ok404=ok404)


def get_list(
path: Optional[str], params: dict = None, ok404: bool = False
) -> List[dict]:
def get_list(path: Optional[str], params: dict = None, ok404: bool = False) -> List[dict]:
"""Uses requests to make a get request.
Will iterate over paginated results and return result as list.
"""
Expand Down Expand Up @@ -468,9 +456,7 @@ def resolve_ip(ip: str) -> str:
cli_error('resolve ip got multiple matches for ip "{}"'.format(ip))

if len(hosts) == 0:
cli_warning(
"{} doesnt belong to any host".format(ip), exception=HostNotFoundWarning
)
cli_warning("{} doesnt belong to any host".format(ip), exception=HostNotFoundWarning)
return hosts[0]["name"]


Expand Down Expand Up @@ -747,22 +733,20 @@ def convert_wildcard_to_regex(
################################################################################


def format_table(
def add_formatted_table_for_output(
headers: Sequence[str],
keys: Sequence[str],
data: List[Dict[str, Any]],
indent: int = 0,
) -> str:
output = ""
manager = OutputManager()
raw_format = " " * indent
for key, header in zip(keys, headers):
longest = len(header)
for d in data:
longest = max(longest, len(str(d[key])))
raw_format += "{:<%d} " % longest

output += raw_format.format(*headers)
manager.add_line(raw_format.format(*headers))
for d in data:
output += raw_format.format(*[d[key] for key in keys])

return output
manager.add_line(raw_format.format(*[d[key] for key in keys]))

0 comments on commit 232b9bc

Please sign in to comment.