xref: /titanic_41/usr/src/lib/pyzfs/common/table.py (revision 67dbe2be0c0f1e2eb428b89088bb5667e8f0b9f6)
1#! /usr/bin/python2.4
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 2009 Sun Microsystems, Inc.  All rights reserved.
23# Use is subject to license terms.
24#
25
26import zfs.util
27
28class Table:
29	__slots__ = "fields", "rjustfields", "maxfieldlen", "lines"
30	__repr__ = zfs.util.default_repr
31
32	def __init__(self, fields, rjustfields=()):
33		# XXX maybe have a defaults, too?
34		self.fields = fields
35		self.rjustfields = rjustfields
36		self.maxfieldlen = dict.fromkeys(fields, 0)
37		self.lines = list()
38
39	def __updatemax(self, k, v):
40		self.maxfieldlen[k] = max(self.maxfieldlen.get(k, None), v)
41
42	def addline(self, sortkey, values):
43		"""values is a dict from field name to value"""
44
45		va = list()
46		for f in self.fields:
47			v = str(values[f])
48			va.append(v)
49			self.__updatemax(f, len(v))
50		self.lines.append((sortkey, va))
51
52	def printme(self, headers=True):
53		if headers:
54			d = dict([(f, f.upper()) for f in self.fields])
55			self.addline(None, d)
56
57		self.lines.sort()
58		for (k, va) in self.lines:
59			line = str()
60			for i in range(len(self.fields)):
61				if not headers:
62					line += va[i]
63					line += "\t"
64				else:
65					if self.fields[i] in self.rjustfields:
66						fmt = "%*s  "
67					else:
68						fmt = "%-*s  "
69					mfl = self.maxfieldlen[self.fields[i]]
70					line += fmt % (mfl, va[i])
71			print(line)
72