icinga2-checks/checker/markdown.py

74 lines
3.2 KiB
Python

def list_to_markdown_table(array, align: str = None, seperator: str = '|', borders: bool = True, right_align_first_item: bool = True):
"""
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'.
seperator:
borders:
right_align_first_item:
"""
# 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
if right_align_first_item:
array = [[elt.ljust(w) if i == 0 else elt.center(w) for i, (elt, w) in enumerate(zip(line, widths))] for line in array]
else:
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
if borders:
edge_seperator = seperator
else:
edge_seperator = ''
if right_align_first_item:
header = ((edge_seperator + ' ') if borders else '') + array_head[0].ljust(widths[0]) + f' {seperator} ' + f' {seperator} '.join([elt.center(w) for elt, w in zip(array_head[1:], widths[1:])]) + ((' ' + edge_seperator) if borders else '')
else:
header = ((edge_seperator + ' ') if borders else '') + f' {seperator} '.join(array_head) + ((' ' + edge_seperator) if borders else '')
# 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
border_left = (edge_seperator + ' ') if borders else ''
border_center = f' {seperator} '
border_right = (' ' + edge_seperator) if borders else ''
elif align == 'center':
border_left = (edge_seperator + ' ') if borders else ''
border_center = f' {seperator} '
border_right = (' ' + edge_seperator) if borders else ''
elif align == 'left':
border_left = (edge_seperator + ' ') if borders else ''
border_center = f' {seperator} '
border_right = (' ' + edge_seperator) if borders else ''
elif align == 'right':
border_left = (edge_seperator + ' ') if borders else ''
border_center = f' {seperator} '
border_right = (' ' + edge_seperator) if borders else ''
else:
raise ValueError("align must be 'left', 'right' or 'center'.")
breaker = border_left + border_center.join(['-' * w for w in widths]) + border_right
# body of the table
del array[0]
body = [''] * len(array) # empty string list that we fill after
for idx, line in enumerate(array):
if borders:
body[idx] = f'{seperator} ' + f' {seperator} '.join(line) + f' {seperator}'
else:
body[idx] = f' {seperator} '.join(line)
body = '\n'.join(body)
return header + '\n' + breaker + '\n' + body