File indexing completed on 2024-12-01 08:16:20

0001 """
0002 Class containing classes for printing tables
0003 """
0004 
0005 # SPDX-FileCopyrightText: 2020 Jonah BrĂ¼chert <jbb@kaidan.im>
0006 #
0007 # SPDX-License-Identifier: GPL-2.0-or-later
0008 
0009 from typing import List
0010 
0011 
0012 class Table:
0013     """
0014     Manages and draws a table to the standard output
0015     """
0016 
0017     __columns: List[List[str]] = []
0018 
0019     def add_column(self, column: List[str]) -> None:
0020         """
0021         Add a column to the table.
0022         The column needs to be a list of strings
0023         """
0024         self.__columns.append(column)
0025 
0026     def add_row(self, row: List[str]) -> None:
0027         """
0028         Add a row to the table.
0029         The row needs to be a list of strings.
0030         """
0031         columns_len: int = Table.__columns_max_len(self.__columns)
0032 
0033         while len(row) > len(self.__columns):
0034             self.__columns.append([])
0035 
0036         for i, item in enumerate(row, 0):
0037             for column in self.__columns:
0038                 while len(column) < columns_len:
0039                     column.append("")
0040 
0041             self.__columns[i].append(item)
0042 
0043     @staticmethod
0044     def __column_max_width(column: List[str]) -> int:
0045         lens: List[int] = []
0046         for string in column:
0047             lens.append(len(string))
0048 
0049         return max(lens)
0050 
0051     @staticmethod
0052     def __columns_max_len(columns: List[List[str]]) -> int:
0053         lens: List[int] = []
0054         for column in columns:
0055             lens.append(len(column))
0056 
0057         try:
0058             return max(lens)
0059         except ValueError:  # Happens if table is completely empty
0060             return 0
0061 
0062     def print(self) -> None:
0063         """
0064         print the table to the terminal
0065         """
0066         # Calculate width for each column
0067         column_widths: List[int] = []
0068         for col in self.__columns:
0069             column_widths.append(self.__column_max_width(col))
0070 
0071         # Build table
0072         for grid_y in range(0, Table.__columns_max_len(self.__columns)):
0073             textbuffer: str = ""
0074 
0075             for grid_x in range(0, len(self.__columns)):
0076                 column: List[str] = self.__columns[grid_x]
0077 
0078                 try:
0079                     textbuffer += column[grid_y]
0080                     textbuffer += (column_widths[grid_x] - len(column[grid_y]) + 2) * " "
0081                 except IndexError:
0082                     textbuffer += (column_widths[grid_x] + 2) * " "
0083 
0084             print(textbuffer)