5969 update illumos-gate to use python2.7
[unleashed.git] / usr / src / lib / pyzfs / common / table.py
blob87aab1d6f1b580754a8fd7c66baa8bd9046bc442
1 #!@PYTHON@
3 # CDDL HEADER START
5 # The contents of this file are subject to the terms of the
6 # Common Development and Distribution License (the "License").
7 # You may not use this file except in compliance with the License.
9 # You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10 # or http://www.opensolaris.org/os/licensing.
11 # See the License for the specific language governing permissions
12 # and limitations under the License.
14 # When distributing Covered Code, include this CDDL HEADER in each
15 # file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16 # If applicable, add the following below this CDDL HEADER, with the
17 # fields enclosed by brackets "[]" replaced with your own identifying
18 # information: Portions Copyright [yyyy] [name of copyright owner]
20 # CDDL HEADER END
22 # Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
25 import zfs.util
27 class Table:
28 __slots__ = "fields", "rjustfields", "maxfieldlen", "lines"
29 __repr__ = zfs.util.default_repr
31 def __init__(self, fields, rjustfields=()):
32 # XXX maybe have a defaults, too?
33 self.fields = fields
34 self.rjustfields = rjustfields
35 self.maxfieldlen = dict.fromkeys(fields, 0)
36 self.lines = list()
38 def __updatemax(self, k, v):
39 self.maxfieldlen[k] = max(self.maxfieldlen.get(k, None), v)
41 def addline(self, sortkey, values):
42 """values is a dict from field name to value"""
44 va = list()
45 for f in self.fields:
46 v = str(values[f])
47 va.append(v)
48 self.__updatemax(f, len(v))
49 self.lines.append((sortkey, va))
51 def printme(self, headers=True):
52 if headers:
53 d = dict([(f, f.upper()) for f in self.fields])
54 self.addline(None, d)
56 self.lines.sort()
57 for (k, va) in self.lines:
58 line = str()
59 for i in range(len(self.fields)):
60 if not headers:
61 line += va[i]
62 line += "\t"
63 else:
64 if self.fields[i] in self.rjustfields:
65 fmt = "%*s "
66 else:
67 fmt = "%-*s "
68 mfl = self.maxfieldlen[self.fields[i]]
69 line += fmt % (mfl, va[i])
70 print(line)