icinga2-checks/checker/markdown.py

66 lines
2.7 KiB
Python
Raw Normal View History

2023-04-21 23:54:18 -06:00
def list_to_markdown_table(array, align: str = None, seperator: str = '|', borders: bool = True):
2023-04-21 23:54:18 -06:00
"""
https://gist.github.com/OsKaR31415/955b166f4a286ed427f667cb21d57bfd
Args:
array: The array to make into a table. Mush be a rectangular array
(constant width and height).
align: The alignment of the cells : 'left', 'center' or 'right'.
2023-04-21 23:54:18 -06:00
seperator:
borders:
2023-04-21 23:54:18 -06:00
"""
# make sure every elements are strings
array = [[str(elt) for elt in line] for line in array]
# get the width of each column
widths = [max(len(line[i]) for line in array) for i in range(len(array[0]))]
# make every width at least 3 colmuns, because the separator needs it
widths = [max(w, 3) for w in widths]
# center text according to the widths
array = [[elt.center(w) for elt, w in zip(line, widths)] for line in array]
# separate the header and the body
array_head, *array_body = array
2023-04-21 23:54:18 -06:00
if borders:
edge_seperator = seperator
else:
edge_seperator = ''
header = ((edge_seperator + ' ') if borders else '') + f' {seperator} '.join(array_head) + ((' ' + edge_seperator) if borders else '')
2023-04-21 23:54:18 -06:00
# alignment of the cells
align = str(align).lower() # make sure `align` is a lowercase string
if align == 'none':
# we are just setting the position of the : in the table.
# here there are none
2023-04-21 23:54:18 -06:00
border_left = (edge_seperator + ' ') if borders else ''
border_center = f' {seperator} '
border_right = (' ' + edge_seperator) if borders else ''
2023-04-21 23:54:18 -06:00
elif align == 'center':
2023-04-21 23:54:18 -06:00
border_left = (edge_seperator + ' ') if borders else ''
border_center = f' {seperator} '
border_right = (' ' + edge_seperator) if borders else ''
2023-04-21 23:54:18 -06:00
elif align == 'left':
2023-04-21 23:54:18 -06:00
border_left = (edge_seperator + ' ') if borders else ''
border_center = f' {seperator} '
border_right = (' ' + edge_seperator) if borders else ''
2023-04-21 23:54:18 -06:00
elif align == 'right':
2023-04-21 23:54:18 -06:00
border_left = (edge_seperator + ' ') if borders else ''
border_center = f' {seperator} '
border_right = (' ' + edge_seperator) if borders else ''
2023-04-21 23:54:18 -06:00
else:
raise ValueError("align must be 'left', 'right' or 'center'.")
2023-04-21 23:54:18 -06:00
breaker = border_left + border_center.join(['-' * w for w in widths]) + border_right
2023-04-21 23:54:18 -06:00
# body of the table
del array[0]
body = [''] * len(array) # empty string list that we fill after
for idx, line in enumerate(array):
2023-04-21 23:54:18 -06:00
if borders:
body[idx] = f'{seperator} ' + f' {seperator} '.join(line) + f' {seperator}'
else:
body[idx] = f' {seperator} '.join(line)
2023-04-21 23:54:18 -06:00
body = '\n'.join(body)
2023-04-21 23:54:18 -06:00
return header + '\n' + breaker + '\n' + body