Backed out changeset b71c8c052463 (bug 1943846) for causing mass failures. CLOSED...
[gecko.git] / tools / lint / perfdocs / doc_helpers.py
blob2f6a793e114540046a2425a4ce19c9fa752692b5
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 class MismatchedRowLengthsException(Exception):
7 """
8 This exception is thrown when there is a mismatch between the number of items in a row,
9 and the number of headers defined.
10 """
12 pass
15 class TableBuilder(object):
16 """
17 Helper class for building tables.
18 """
20 def __init__(self, title, widths, header_rows, headers, indent=0):
21 """
22 :param title: str - Title of the table
23 :param widths: list of str - Widths of each column of the table
24 :param header_rows: int - Number of header rows
25 :param headers: 2D list of str - Headers
26 :param indent: int - Number of spaces to indent table
27 """
28 if not isinstance(title, str):
29 raise TypeError("TableBuilder attribute title must be a string.")
30 if not isinstance(widths, list) or not isinstance(widths[0], int):
31 raise TypeError("TableBuilder attribute widths must be a list of integers.")
32 if not isinstance(header_rows, int):
33 raise TypeError("TableBuilder attribute header_rows must be an integer.")
34 if (
35 not isinstance(headers, list)
36 or not isinstance(headers[0], list)
37 or not isinstance(headers[0][0], str)
39 raise TypeError(
40 "TableBuilder attribute headers must be a two-dimensional list of strings."
42 if not isinstance(indent, int):
43 raise TypeError("TableBuilder attribute indent must be an integer.")
45 self.title = title
46 self.widths = widths
47 self.header_rows = header_rows
48 self.headers = headers
49 self.indent = " " * indent
50 self.table = ""
51 self._build_table()
53 def _build_table(self):
54 if len(self.widths) != len(self.headers[0]):
55 raise MismatchedRowLengthsException(
56 "Number of table headers must match number of column widths."
58 widths = " ".join(map(str, self.widths))
59 self.table += (
60 f"{self.indent}.. list-table:: **{self.title}**\n"
61 f"{self.indent} :widths: {widths}\n"
62 f"{self.indent} :header-rows: {self.header_rows}\n\n"
64 self.add_rows(self.headers)
66 def add_rows(self, rows):
67 if (
68 type(rows) is not list
69 or type(rows[0]) is not list
70 or type(rows[0][0]) is not str
72 raise TypeError("add_rows() requires a two-dimensional list of strings.")
73 for row in rows:
74 self.add_row(row)
76 def add_row(self, values):
77 if len(values) != len(self.widths):
78 raise MismatchedRowLengthsException(
79 "Number of items in a row must must number of columns defined."
81 for i, val in enumerate(values):
82 if i == 0:
83 self.table += f"{self.indent} * - **{val}**\n"
84 else:
85 self.table += f"{self.indent} - {val}\n"
87 def finish_table(self):
88 self.table += "\n"
89 return self.table