1 # Text wrapper for ldb bindings
3 # Copyright (C) 2015 Petr Viktorin <pviktori@redhat.com>
4 # Published under the GNU LGPLv3 or later
12 def _recursive_encode(obj):
13 if isinstance(obj, bytes):
15 elif isinstance(obj, str):
16 return obj.encode('utf-8')
18 return [_recursive_encode(o) for o in obj]
21 class _WrapBase(object):
24 def _wrap(cls, wrapped):
25 self = cls.__new__(cls)
26 self._wrapped = wrapped
30 return len(self._wrapped)
32 def __eq__(self, other):
33 if hasattr(other, '_wrapped'):
34 return self._wrapped == other._wrapped
36 return self._wrapped == other
38 def __ne__(self, other):
39 if hasattr(other, '_wrapped'):
40 return self._wrapped != other._wrapped
42 return self._wrapped != other
44 def __lt__(self, other):
45 if hasattr(other, '_wrapped'):
46 return self._wrapped < other._wrapped
48 return self._wrapped < other
50 def __le__(self, other):
51 if hasattr(other, '_wrapped'):
52 return self._wrapped >= other._wrapped
54 return self._wrapped >= other
56 def __gt__(self, other):
57 if hasattr(other, '_wrapped'):
58 return self._wrapped > other._wrapped
60 return self._wrapped > other
62 def __ge__(self, other):
63 if hasattr(other, '_wrapped'):
64 return self._wrapped >= other._wrapped
66 return self._wrapped >= other
69 return '%s.text' % repr(self._wrapped)
72 class MessageElementTextWrapper(_WrapBase):
74 """Text interface for a LDB message element"""
77 for item in self._wrapped:
78 yield item.decode('utf-8')
80 def __getitem__(self, key):
81 result = self._wrapped[key]
85 return result.decode('utf-8')
89 return self._wrapped.flags
93 return self._wrapped.set_flags
95 _wrap_element = MessageElementTextWrapper._wrap
98 class MessageTextWrapper(_WrapBase):
100 """Text interface for a LDB message"""
102 def __getitem__(self, key):
103 result = self._wrapped[key]
107 return _wrap_element(result)
109 def get(self, *args, **kwargs):
110 result = self._wrapped.get(*args, **kwargs)
111 if isinstance(result, ldb.MessageElement):
112 return _wrap_element(result)
113 elif isinstance(result, bytes):
114 return result.decode('utf-8')
118 def __setitem__(self, key, item):
119 self._wrapped[key] = _recursive_encode(item)
121 def __delitem__(self, key):
122 del self._wrapped[key]
125 return [_wrap_element(el) for el in self._wrapped.elements()]
128 return [(attr, _wrap_element(el)) for attr, el in self._wrapped.items()]
132 return self._wrapped.keys
136 return self._wrapped.remove
140 return self._wrapped.add
144 return self._wrapped.dn
147 def dn(self, new_value):
148 self._wrapped.dn = new_value