Joe Onorato | 88ede35 | 2023-12-19 02:56:38 +0000 | [diff] [blame] | 1 | # 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 | |
| 17 | class Sentinel(): |
| 18 | pass |
| 19 | |
| 20 | SEPARATOR = Sentinel() |
| 21 | |
Joe Onorato | 6b40826 | 2024-01-19 16:35:02 +0000 | [diff] [blame^] | 22 | def FormatTable(data, prefix="", alignments=[]): |
Joe Onorato | 88ede35 | 2023-12-19 02:56:38 +0000 | [diff] [blame] | 23 | """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 Onorato | 6b40826 | 2024-01-19 16:35:02 +0000 | [diff] [blame^] | 43 | if i >= len(alignments) or alignments[i] == "R": |
Joe Onorato | 88ede35 | 2023-12-19 02:56:38 +0000 | [diff] [blame] | 44 | result += " " * (widths[i] - len(cell)) |
| 45 | result += cell |
Joe Onorato | 6b40826 | 2024-01-19 16:35:02 +0000 | [diff] [blame^] | 46 | if i < len(alignments) and alignments[i] == "L": |
Joe Onorato | 88ede35 | 2023-12-19 02:56:38 +0000 | [diff] [blame] | 47 | result += " " * (widths[i] - len(cell)) |
| 48 | result += colsep |
| 49 | result += "\n" |
| 50 | return result |
| 51 | |
| 52 | |