4 # Copyright (c) 2011 Thomas Graf <tgraf@suug.ch>
7 """utility module for netlink
11 from __future__ import absolute_import
13 from . import core as netlink
14 from . import capi as capi
15 from string import Formatter
21 return b'{esc}[{color}m{text}{esc}[0m'.format(esc=b'\x1b', color=c, text=t)
77 class MyFormatter(Formatter):
78 def __init__(self, obj, indent=''):
82 def _nlattr(self, key):
83 value = getattr(self._obj.__class__, key)
84 if not isinstance(value, property):
85 raise ValueError('Invalid formatting string {0}'.format(key))
87 d = getattr(value.fget, 'formatinfo', dict())
89 # value = value.fget() is exactly the same
90 value = getattr(self._obj, key)
93 value = d['fmt'](value)
95 title_ = d.get('title', None)
97 return title_, str(value)
99 def get_value(self, key, args, kwds):
100 # Let default get_value() handle ints
101 if not isinstance(key, str):
102 return Formatter.get_value(self, key, args, kwds)
104 # HACK, we allow defining strings via fields to allow
110 # title mode ("TITLE ATTR")
112 elif key[:2] == 'a|':
113 # plain attribute mode ("ATTR")
114 include_title = False
116 # No special field, have default get_value() get it
117 return Formatter.get_value(self, key, args, kwds)
120 (title_, value) = self._nlattr(key)
124 title_ = key # fall back to key as title
125 value = '{0} {1}'.format(kw(title_), value)
129 def convert_field(self, value, conversion):
130 if conversion == 'r':
132 elif conversion == 's':
134 elif conversion == 'k':
136 elif conversion == 'b':
138 elif conversion is None:
141 raise ValueError('Unknown converion specifier {0!s}'.format(conversion))
143 def nl(self, format_string=''):
144 return '\n' + self._indent + self.format(format_string)
150 def __init__(self, rate, mode=NL_BYTE_RATE):
155 return capi.nl_rate2str(self._rate, self._mode, 32)[1]
160 def __cmp__(self, other):
161 return int(self) - int(other)
164 def __init__(self, size):
168 return capi.nl_size2str(self._size, 32)[0]
173 def __cmp__(self, other):
174 return int(self) - int(other)