xref: /titanic_50/usr/src/lib/pyzfs/common/table.py (revision 8cfa78e6de0de88f6a15cd29ee5f6a8a1bfe7c20)
1#!@PYTHON@
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# Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
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		if sortkey == None:
51			sortkey = []
52		self.lines.append((sortkey, va))
53
54	def printme(self, headers=True):
55		if headers:
56			d = dict([(f, f.upper()) for f in self.fields])
57			self.addline(None, d)
58
59		self.lines.sort()
60		for (k, va) in self.lines:
61			line = str()
62			for i in range(len(self.fields)):
63				if not headers:
64					line += va[i]
65					line += "\t"
66				else:
67					if self.fields[i] in self.rjustfields:
68						fmt = "%*s  "
69					else:
70						fmt = "%-*s  "
71					mfl = self.maxfieldlen[self.fields[i]]
72					line += fmt % (mfl, va[i])
73			print(line)
74