Debian Codegraph @

cli_helpers/tabular_output/vertical_table_adapter.py

raw
1 # -*- coding: utf-8 -*-
2 """Format data into a vertical table layout."""
3
4 from __future__ import unicode_literals
5
6 from cli_helpers.utils import filter_dict_by_key
7 from .preprocessors import convert_to_string, override_missing_value, style_output
8
9 supported_formats = ("vertical",)
10 preprocessors = (override_missing_value, convert_to_string, style_output)
11
12
13 def _get_separator(num, sep_title, sep_character, sep_length):
14 """Get a row separator for row *num*."""
15 left_divider_length = right_divider_length = sep_length
16 if isinstance(sep_length, tuple):
17 left_divider_length, right_divider_length = sep_length
18 left_divider = sep_character * left_divider_length
19 right_divider = sep_character * right_divider_length
20 title = sep_title.format(n=num + 1)
21
22 return "{left_divider}[ {title} ]{right_divider}\n".format(
23 left_divider=left_divider, right_divider=right_divider, title=title
24 )
25
26
27 def _format_row(headers, row):
28 """Format a row."""
29 formatted_row = [" | ".join(field) for field in zip(headers, row)]
30 return "\n".join(formatted_row)
31
32
33 def vertical_table(
34 data, headers, sep_title="{n}. row", sep_character="*", sep_length=27
35 ):
36 """Format *data* and *headers* as an vertical table.
37
38 The values in *data* and *headers* must be strings.
39
40 :param iterable data: An :term:`iterable` (e.g. list) of rows.
41 :param iterable headers: The column headers.
42 :param str sep_title: The title given to each row separator. Defaults to
43 ``'{n}. row'``. Any instance of ``'{n}'`` is
44 replaced by the record number.
45 :param str sep_character: The character used to separate rows. Defaults to
46 ``'*'``.
47 :param int/tuple sep_length: The number of separator characters that should
48 appear on each side of the *sep_title*. Use
49 a tuple to specify the left and right values
50 separately.
51 :return: The formatted data.
52 :rtype: str
53
54 """
55 if data and not headers:
56 headers = [" " * len(x) for x in data[0]]
57 header_len = max(len(x) for x in headers or [""])
58 padded_headers = [x.ljust(header_len) for x in headers]
59 formatted_rows = [_format_row(padded_headers, row) for row in data]
60
61 output = []
62 for i, result in enumerate(formatted_rows):
63 yield _get_separator(i, sep_title, sep_character, sep_length) + result
64
65
66 def adapter(data, headers, **kwargs):
67 """Wrap vertical table in a function for TabularOutputFormatter."""
68 keys = ("sep_title", "sep_character", "sep_length")
69 return vertical_table(data, headers, **filter_dict_by_key(kwargs, keys))