blob: 14fdc9ed8d98c977bd3ddcd556b2f25dadf1bc55 [file] [log] [blame]
Joe Onorato88ede352023-12-19 02:56:38 +00001# Copyright (C) 2023 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15# Formatting utilities
16
17class Sentinel():
18 pass
19
20SEPARATOR = Sentinel()
21
Joe Onorato6b408262024-01-19 16:35:02 +000022def FormatTable(data, prefix="", alignments=[]):
Joe Onorato88ede352023-12-19 02:56:38 +000023 """Pretty print a table.
24
25 Prefixes each row with `prefix`.
26 """
27 if not data:
28 return ""
29 widths = [max([len(x) if x else 0 for x in col]) for col
30 in zip(*[d for d in data if not isinstance(d, Sentinel)])]
31 result = ""
32 colsep = " "
33 for row in data:
34 result += prefix
35 if row == SEPARATOR:
36 for w in widths:
37 result += "-" * w
38 result += colsep
39 result += "\n"
40 else:
41 for i in range(len(row)):
42 cell = row[i] if row[i] else ""
Joe Onorato6b408262024-01-19 16:35:02 +000043 if i >= len(alignments) or alignments[i] == "R":
Joe Onorato88ede352023-12-19 02:56:38 +000044 result += " " * (widths[i] - len(cell))
45 result += cell
Joe Onorato6b408262024-01-19 16:35:02 +000046 if i < len(alignments) and alignments[i] == "L":
Joe Onorato88ede352023-12-19 02:56:38 +000047 result += " " * (widths[i] - len(cell))
48 result += colsep
49 result += "\n"
50 return result
51
52