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 17class Sentinel(): 18 pass 19 20SEPARATOR = Sentinel() 21 22def FormatTable(data, prefix="", alignments=[]): 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 "" 43 if i >= len(alignments) or alignments[i] == "R": 44 result += " " * (widths[i] - len(cell)) 45 result += cell 46 if i < len(alignments) and alignments[i] == "L": 47 result += " " * (widths[i] - len(cell)) 48 result += colsep 49 result += "\n" 50 return result 51 52 53