Skip to content

Commit

Permalink
add ability to adjust column widths via CLI
Browse files Browse the repository at this point in the history
  • Loading branch information
danielfromearth committed Oct 23, 2023
1 parent 2d22ea5 commit 5154b40
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
8 changes: 8 additions & 0 deletions ncompare/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ def _cli() -> argparse.Namespace:
help="Include chunk sizes in the table that compares variables",
)

parser.add_argument(
"--column-widths",
nargs=3,
default=None,
type=int,
help="Width, in number of characters, of the three columns in the comparison report",
)

return parser.parse_args()


Expand Down
6 changes: 5 additions & 1 deletion ncompare/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def compare(
file_text: Union[str, Path] = "",
file_csv: Union[str, Path] = "",
file_xlsx: Union[str, Path] = "",
column_widths: Optional[tuple[int | str, int | str, int | str]] = None,
) -> None:
"""Compare the variables contained within two different NetCDF datasets.
Expand All @@ -58,6 +59,8 @@ def compare(
filepath destination to save comparison output as comma-separated values (CSV).
file_xlsx : str
filepath destination to save comparison output as an Excel workbook.
column_widths : tuple[int | str, int | str, int | str], optional
the width in number of characters for each column of the comparison table.
Returns
-------
Expand All @@ -74,7 +77,8 @@ def compare(
file_xlsx = ensure_valid_path_with_suffix(file_xlsx, ".xlsx")

# The Outputter object is initialized to handle stdout and optional writing to a text file.
with Outputter(keep_print_history=True, no_color=no_color, text_file=file_text) as out:
with Outputter(keep_print_history=True, no_color=no_color, text_file=file_text,
column_widths=column_widths) as out:
out.print(f"File A: {nc_a}")
out.print(f"File B: {nc_b}")
out.side_by_side(' ', str(nc_a), str(nc_b))
Expand Down
30 changes: 28 additions & 2 deletions ncompare/printing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# pylint: disable=too-many-arguments
import csv
import re
import warnings
from collections.abc import Iterable
from pathlib import Path
from typing import Optional, TextIO, Union
Expand Down Expand Up @@ -42,6 +43,7 @@ def __init__(
keep_print_history: bool = False,
no_color: bool = False,
text_file: Optional[Union[str, Path]] = None,
column_widths: Optional[tuple[int | str, int | str, int | str]] = None
):
"""Set up the handling of printing and saving destinations.
Expand All @@ -53,6 +55,24 @@ def __init__(
self._keep_print_history = keep_print_history
self._line_history: list[list[str]] = []

# Assign column widths according to input, if
default_widths = [33, 48, 48]
if column_widths is not None:
assert len(column_widths) == 3

new_widths = default_widths
for idx, width in enumerate(column_widths):
if isinstance(width, str) and width.isdigit() and (int(width) > 0):
# note: isdigit() ensures integer
new_widths[idx] = int(width)
elif isinstance(width, int) and width > 0:
new_widths[idx] = width
else:
warnings.warn("Column-width input was not a positive integer. Reverting to default.")
self._column_widths = new_widths
else:
self._column_widths = tuple(default_widths)

if no_color:
# Replace colorized styles with blank strings.
for k, _ in Fore.__dict__.items():
Expand Down Expand Up @@ -173,9 +193,15 @@ def side_by_side(self, str_a, str_b, str_c, dash_line=False, highlight_diff=Fals
str_marker = ""

if dash_line:
self.print(f" {extra_style_space}{str_a:>33} {str_b:->48} {str_c:->48}", colors=colors)
self.print(f" {extra_style_space}"
f"{str_a:>{self._column_widths[0]}} "
f"{str_b:->{self._column_widths[1]}} "
f"{str_c:->{self._column_widths[2]}}", colors=colors)
else:
self.print(f" {extra_style_space}{str_a:>33} {str_b:>48} {str_c:>48}", colors=colors)
self.print(f" {extra_style_space}"
f"{str_a:>{self._column_widths[0]}} "
f"{str_b:>{self._column_widths[1]}} "
f"{str_c:>{self._column_widths[2]}}", colors=colors)

self._add_to_history(str_a, str_b, str_c, str_marker)

Expand Down

0 comments on commit 5154b40

Please sign in to comment.