xref: /titanic_52/usr/src/lib/pyzfs/common/table.py (revision 263f549e5da8b32c4922f586afb365b8ae388a6c)
1#! /usr/bin/python2.6
2#
3# CDDL HEADER START
4#
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.
8#
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.
13#
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]
19#
20# CDDL HEADER END
21#
22# Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
23#
24
25import zfs.util
26
27class Table:
28	__slots__ = "fields", "rjustfields", "maxfieldlen", "lines"
29	__repr__ = zfs.util.default_repr
30
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()
37
38	def __updatemax(self, k, v):
39		self.maxfieldlen[k] = max(self.maxfieldlen.get(k, None), v)
40
41	def addline(self, sortkey, values):
42		"""values is a dict from field name to value"""
43
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))
50
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)
55
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)
71