blob: 867aa3b8397aa51b328e4b03dd661d4d5d5382fb [file] [log] [blame]
Zsolt Haraszti80175202016-12-24 00:17:51 -08001#
2# Copyright 2016 the original author or authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16import sys
17
18from google.protobuf.message import Message
19from termcolor import colored
20
21_printfn = lambda l: sys.stdout.write(l + '\n')
22
23
24class TablePrinter(object):
25 """Simple tabular data printer utility. For usage, see bottom of file"""
26
27 def __init__(self):
28 self.max_field_lengths = {}
29 self.field_names = {}
30 self.cell_values = {}
31
32 def add_cell(self, row_number, field_key, field_name, value):
33 if not isinstance(value, str):
34 value = str(value)
35 self._add_field_type(field_key, field_name)
36 row = self.cell_values.setdefault(row_number, {})
37 row[field_key] = value
38 self._update_max_length(field_key, value)
39
Zsolt Haraszti85f12852016-12-24 08:30:58 -080040 def number_of_rows(self):
41 return len(self.cell_values)
42
Zsolt Haraszti80175202016-12-24 00:17:51 -080043 def print_table(self, header=None, printfn=_printfn, dividers=10):
44
45 if header is not None:
46 printfn(header)
47
48 field_keys = sorted(self.field_names.keys())
49
50 if not field_keys:
51 printfn('table empty')
52 return
53
54 def p_sep():
55 printfn('+' + '+'.join(
56 [(self.max_field_lengths[k] + 2) * '-'
57 for k in field_keys]) + '+')
58
59 p_sep()
60
61 printfn('| ' + ' | '.join(
62 '%%%ds' % self.max_field_lengths[k] % self.field_names[k]
63 for k in field_keys) + ' |')
64 p_sep()
65
66 for i in range(len(self.cell_values)):
67 row = self.cell_values[i]
68 printfn(colored('| ' + ' | '.join(
69 '%%%ds' % self.max_field_lengths[k] % row.get(k, '')
70 for k in field_keys
71 ) + ' |'))
72 if not ((i + 1) % dividers):
73 p_sep()
74
75 if (i + 1) % dividers:
76 p_sep()
77
78 def _update_max_length(self, field_key, string):
79 length = len(string)
80 if length > self.max_field_lengths.get(field_key, 0):
81 self.max_field_lengths[field_key] = length
82
83 def _add_field_type(self, field_key, field_name):
84 if field_key not in self.field_names:
85 self.field_names[field_key] = field_name
86 self._update_max_length(field_key, field_name)
Sergio Slobodrianb5ef3482017-03-17 16:56:16 -040087 else:
88 assert self.field_names[field_key] == field_name
Zsolt Haraszti80175202016-12-24 00:17:51 -080089
90
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -040091def print_pb_list_as_table(header, items, fields_to_omit=None,
Sergio Slobodriana95f99b2017-03-21 10:22:47 -040092 printfn=_printfn, dividers=10, show_nulls=False):
Zsolt Haraszti80175202016-12-24 00:17:51 -080093 from cli.utils import pb2dict
94
95 t = TablePrinter()
96 for row, obj in enumerate(items):
97 assert isinstance(obj, Message)
98
khenaidooa00efaf2017-11-15 16:17:10 -050099 def set_row(pd_dict, _row, field, value, t, prefix,
khenaidoo079a7762017-10-26 21:42:05 -0400100 fields_to_omit, number):
101 fname = prefix + field.name
102 if fname in fields_to_omit:
103 return
104 if isinstance(value, Message):
105 add(_row, value, fname + '.',
106 100 * (number + field.number))
107 else:
108 t.add_cell(_row, number + field.number, fname,
khenaidooa00efaf2017-11-15 16:17:10 -0500109 pd_dict.get(field.name))
khenaidoo079a7762017-10-26 21:42:05 -0400110
Zsolt Haraszti80175202016-12-24 00:17:51 -0800111 def add(_row, pb, prefix='', number=0):
112 d = pb2dict(pb)
Sergio Slobodriana95f99b2017-03-21 10:22:47 -0400113 if show_nulls:
114 fields = pb.DESCRIPTOR.fields
khenaidoo079a7762017-10-26 21:42:05 -0400115 for field in fields:
khenaidooa00efaf2017-11-15 16:17:10 -0500116 set_row(d,
117 _row,
khenaidoo079a7762017-10-26 21:42:05 -0400118 field,
khenaidoo079a7762017-10-26 21:42:05 -0400119 getattr(pb, field.name),
120 t,
121 prefix,
122 fields_to_omit,
123 number)
Sergio Slobodriana95f99b2017-03-21 10:22:47 -0400124 else:
khenaidoo079a7762017-10-26 21:42:05 -0400125 fields = pb.ListFields()
126 for (field, value) in fields:
khenaidooa00efaf2017-11-15 16:17:10 -0500127 set_row(d,
128 _row,
khenaidoo079a7762017-10-26 21:42:05 -0400129 field,
khenaidoo079a7762017-10-26 21:42:05 -0400130 value,
131 t,
132 prefix,
133 fields_to_omit,
134 number)
Zsolt Haraszti80175202016-12-24 00:17:51 -0800135 add(row, obj)
136
Sergio Slobodrian901bf4e2017-03-17 12:54:39 -0400137 t.print_table(header, printfn, dividers)
Zsolt Haraszti80175202016-12-24 00:17:51 -0800138
139
Sergio Slobodriana95f99b2017-03-21 10:22:47 -0400140def print_pb_as_table(header, pb, fields_to_omit={}, printfn=_printfn,
141 show_nulls=False):
khenaidooa00efaf2017-11-15 16:17:10 -0500142
Zsolt Haraszti85f12852016-12-24 08:30:58 -0800143 from cli.utils import pb2dict
144
khenaidooa00efaf2017-11-15 16:17:10 -0500145 def is_repeated_item(msg):
146 return hasattr(msg, "extend")
147
khenaidoo079a7762017-10-26 21:42:05 -0400148 def set_cell(pb, field, value, t, prefix, fields_to_omit):
khenaidooa00efaf2017-11-15 16:17:10 -0500149 d = pb2dict(pb)
khenaidoo079a7762017-10-26 21:42:05 -0400150 fname = prefix + field.name
khenaidooa00efaf2017-11-15 16:17:10 -0500151
khenaidoo079a7762017-10-26 21:42:05 -0400152 if fname in fields_to_omit:
153 return
154 if isinstance(value, Message):
155 pr(value, fname + '.')
khenaidooa00efaf2017-11-15 16:17:10 -0500156 elif is_repeated_item(value): # handles any list
khenaidoo079a7762017-10-26 21:42:05 -0400157 row = t.number_of_rows()
158 t.add_cell(row, 0, 'field', fname)
khenaidooa00efaf2017-11-15 16:17:10 -0500159 t.add_cell(row, 1, 'value',
160 '{} item(s)'.format(len(d.get(field.name))))
khenaidoo079a7762017-10-26 21:42:05 -0400161 else:
162 row = t.number_of_rows()
163 t.add_cell(row, 0, 'field', fname)
khenaidooa00efaf2017-11-15 16:17:10 -0500164 t.add_cell(row, 1, 'value', value)
165
khenaidoo079a7762017-10-26 21:42:05 -0400166
Zsolt Haraszti85f12852016-12-24 08:30:58 -0800167 t = TablePrinter()
168
169 def pr(_pb, prefix=''):
Sergio Slobodriana95f99b2017-03-21 10:22:47 -0400170 if show_nulls:
171 fields = _pb.DESCRIPTOR.fields
khenaidoo079a7762017-10-26 21:42:05 -0400172 for field in sorted(fields, key=lambda f: f.number):
173 set_cell(_pb,
174 field,
175 getattr(_pb, field.name),
176 t,
177 prefix,
178 fields_to_omit)
Sergio Slobodriana95f99b2017-03-21 10:22:47 -0400179 else:
khenaidoo079a7762017-10-26 21:42:05 -0400180 fields = _pb.ListFields()
181 for (field, value) in sorted(fields, key=lambda (f, v): f.number):
182 set_cell(_pb,
183 field,
184 value,
185 t,
186 prefix,
187 fields_to_omit)
Zsolt Haraszti85f12852016-12-24 08:30:58 -0800188
189 pr(pb)
190
191 t.print_table(header, printfn)
192
khenaidoo079a7762017-10-26 21:42:05 -0400193
Zsolt Haraszti80175202016-12-24 00:17:51 -0800194if __name__ == '__main__':
195 import random
khenaidoo079a7762017-10-26 21:42:05 -0400196
Zsolt Haraszti80175202016-12-24 00:17:51 -0800197 t = TablePrinter()
198 for row in range(10):
199 t.add_cell(row, 0, 'id', row + 100)
200 t.add_cell(row, 1, 'name', 'Joe Somebody')
201 t.add_cell(row, 2, 'ows', '${}'.format(random.randint(10, 100000)))
202 t.print_table()