Initial commit

This commit is contained in:
David Beazley
2023-07-16 20:21:00 -05:00
parent 82e815fab2
commit 7d4b30154a
259 changed files with 600233 additions and 2 deletions

View File

@@ -0,0 +1,5 @@
# __init__.py
from .formatter import print_table, create_formatter
__all__ = [ 'print_table', 'create_formatter' ]

View File

@@ -0,0 +1,2 @@
# formats/__init__.py

View File

@@ -0,0 +1,10 @@
# csv.py
from ..formatter import TableFormatter
class CSVTableFormatter(TableFormatter):
def headings(self, headers):
print(','.join(headers))
def row(self, rowdata):
print(','.join(str(d) for d in rowdata))

View File

@@ -0,0 +1,16 @@
# html.py
from ..formatter import TableFormatter
class HTMLTableFormatter(TableFormatter):
def headings(self, headers):
print('<tr>', end=' ')
for h in headers:
print('<th>%s</th>' % h, end=' ')
print('</tr>')
def row(self, rowdata):
print('<tr>', end=' ')
for d in rowdata:
print('<td>%s</td>' % d, end=' ')
print('</tr>')

View File

@@ -0,0 +1,11 @@
# text.py
from ..formatter import TableFormatter
class TextTableFormatter(TableFormatter):
def headings(self, headers):
print(' '.join('%10s' % h for h in headers))
print(('-'*10 + ' ')*len(headers))
def row(self, rowdata):
print(' '.join('%10s' % d for d in rowdata))

View File

@@ -0,0 +1,9 @@
# tsv.py
from ..formatter import TableFormatter
class TSVTableFormatter(TableFormatter):
def headings(self, headers):
print('\t'.join(headers))
def row(self, rowdata):
print('\t'.join(str(d) for d in rowdata))

View File

@@ -0,0 +1,58 @@
# tableformat.py
from abc import ABC, abstractmethod
def print_table(records, fields, formatter):
if not isinstance(formatter, TableFormatter):
raise RuntimeError('Expected a TableFormatter')
formatter.headings(fields)
for r in records:
rowdata = [getattr(r, fieldname) for fieldname in fields]
formatter.row(rowdata)
class TableFormatter(ABC):
_formats = { }
@classmethod
def __init_subclass__(cls):
name = cls.__module__.split('.')[-1]
TableFormatter._formats[name] = cls
@abstractmethod
def headings(self, headers):
pass
@abstractmethod
def row(self, rowdata):
pass
class ColumnFormatMixin:
formats = []
def row(self, rowdata):
rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)]
super().row(rowdata)
class UpperHeadersMixin:
def headings(self, headers):
super().headings([h.upper() for h in headers])
def create_formatter(name, column_formats=None, upper_headers=False):
if name not in TableFormatter._formats:
__import__(f'{__package__}.formats.{name}')
formatter_cls = TableFormatter._formats.get(name)
if not formatter_cls:
raise RuntimeError('Unknown format %s' % name)
if column_formats:
class formatter_cls(ColumnFormatMixin, formatter_cls):
formats = column_formats
if upper_headers:
class formatter_cls(UpperHeadersMixin, formatter_cls):
pass
return formatter_cls()