enhance formatters

This commit is contained in:
Christophe Benz 2010-07-11 22:00:18 +02:00
commit 5547e14e11
8 changed files with 196 additions and 65 deletions

View file

@ -27,7 +27,7 @@ from weboob.core import CallErrors
from weboob.core.modules import BackendsConfig
from .base import BackendNotFound, BaseApplication
from .formatters.instances import formatters
from .formatters.load import formatters, load_formatter
from .results import ResultsCondition, ResultsConditionException
@ -60,8 +60,7 @@ class ConsoleApplication(BaseApplication):
results_options = OptionGroup(self._parser, 'Results Options')
results_options.add_option('-c', '--condition', help='filter result items to display given a boolean condition')
results_options.add_option('-f', '--formatter', default='multiline', choices=formatters.keys(),
help='select output formatter (%s)' % u','.join(formatters.keys()))
results_options.add_option('-f', '--formatter', choices=formatters, help='select output formatter (%s)' % u','.join(formatters))
results_options.add_option('-s', '--select', help='select result item key(s) to display (comma-separated)')
self._parser.add_option_group(results_options)
@ -73,7 +72,11 @@ class ConsoleApplication(BaseApplication):
pass
def _handle_app_options(self):
self.formatter = formatters[self.options.formatter]
if self.options.formatter:
formatter_name = self.options.formatter
else:
formatter_name = 'multiline'
self.formatter = load_formatter(formatter_name)
if self.options.no_header:
self.formatter.display_header = False
@ -205,7 +208,11 @@ class ConsoleApplication(BaseApplication):
def command(doc_string, f=register_command):
return partial(f, doc_string=doc_string)
def set_header(self, string):
def set_default_formatter(self, name):
if not self.options.formatter:
self.formatter = load_formatter(name)
def set_formatter_header(self, string):
self.formatter.set_header(string)
def format(self, result, backend_name=None):

View file

@ -43,7 +43,8 @@ class IFormatter(object):
call it. It can be used to specify the fields order.
@param obj [object] object to format
@param selected_fields [list] fields to display. If None, all fields are selected.
@param backend_name [str] name of backend, used to create object ID
@param selected_fields [tuple] fields to display. If None, all fields are selected
@param condition [Condition] condition to objects to display
@return a string of the formatted object
"""

View file

@ -15,30 +15,28 @@
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
from .multiline import MultilineFormatter
from .simple import SimpleFormatter
__all__ = ['load_formatter']
__all__ = ['formatters']
formatters = ('htmltable', 'multiline', 'simple', 'table', 'webkit')
formatters = dict(
multiline=MultilineFormatter(),
simple=SimpleFormatter(),
)
try:
from .table import TableFormatter
formatters.update(dict(
table=TableFormatter(),
htmltable=TableFormatter(result_funcname='get_html_string'),
))
try:
def load_formatter(name):
if name not in formatters:
raise Exception(u'Formatter "%s" not found' % name)
if name in ('htmltable', 'table'):
from .table import TableFormatter
if name == 'htmltable':
return TableFormatter(result_funcname='get_html_string')
elif name == 'table':
return TableFormatter()
elif name == 'simple':
from .simple import SimpleFormatter
return SimpleFormatter()
elif name == 'multiline':
from .multiline import MultilineFormatter
return MultilineFormatter()
elif name == 'webkit':
from .webkit import WebkitGtkFormatter
formatters.update(dict(
webkit=WebkitGtkFormatter(),
))
except ImportError:
pass
except ImportError:
pass
return WebkitGtkFormatter()

View file

@ -48,7 +48,7 @@ class TableFormatter(IFormatter):
elif self.result_funcname == 'get_html_string':
s+= '<p>%s</p>' % self.header
s += "\n"
table = PrettyTable(self.column_headers)
table = PrettyTable(list(self.column_headers))
for column_header in self.column_headers:
table.set_field_align(column_header, 'l')
for line in self.queue:

124
weboob/tools/ordereddict.py Normal file
View file

@ -0,0 +1,124 @@
# -*- coding: utf-8 -*-
# Copyright(C) 2010 Christophe Benz
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
try:
from ordereddict import OrderedDict
except:
## {{{ http://code.activestate.com/recipes/576693/ (r6)
from UserDict import DictMixin
class OrderedDict(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except AttributeError:
self.clear()
self.update(*args, **kwds)
def clear(self):
self.__end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.__map = {} # key --> [key, prev, next]
dict.clear(self)
def __setitem__(self, key, value):
if key not in self:
end = self.__end
curr = end[1]
curr[2] = end[1] = self.__map[key] = [key, curr, end]
dict.__setitem__(self, key, value)
def __delitem__(self, key):
dict.__delitem__(self, key)
key, prev, next = self.__map.pop(key)
prev[2] = next
next[1] = prev
def __iter__(self):
end = self.__end
curr = end[2]
while curr is not end:
yield curr[0]
curr = curr[2]
def __reversed__(self):
end = self.__end
curr = end[1]
while curr is not end:
yield curr[0]
curr = curr[1]
def popitem(self, last=True):
if not self:
raise KeyError('dictionary is empty')
if last:
key = reversed(self).next()
else:
key = iter(self).next()
value = self.pop(key)
return key, value
def __reduce__(self):
items = [[k, self[k]] for k in self]
tmp = self.__map, self.__end
del self.__map, self.__end
inst_dict = vars(self).copy()
self.__map, self.__end = tmp
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def keys(self):
return list(self)
setdefault = DictMixin.setdefault
update = DictMixin.update
pop = DictMixin.pop
values = DictMixin.values
items = DictMixin.items
iterkeys = DictMixin.iterkeys
itervalues = DictMixin.itervalues
iteritems = DictMixin.iteritems
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
def copy(self):
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
d = cls()
for key in iterable:
d[key] = value
return d
def __eq__(self, other):
if isinstance(other, OrderedDict):
return len(self)==len(other) and self.items() == other.items()
return dict.__eq__(self, other)
def __ne__(self, other):
return not self == other
## end of http://code.activestate.com/recipes/576693/ }}}