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
96 _wrap_element = MessageElementTextWrapper._wrap
99 class MessageTextWrapper(_WrapBase):
101 """Text interface for a LDB message"""
103 def __getitem__(self, key):
104 result = self._wrapped[key]
108 return _wrap_element(result)
110 def get(self, *args, **kwargs):
111 result = self._wrapped.get(*args, **kwargs)
112 if isinstance(result, ldb.MessageElement):
113 return _wrap_element(result)
114 elif isinstance(result, bytes):
115 return result.decode('utf-8')
119 def __setitem__(self, key, item):
120 self._wrapped[key] = _recursive_encode(item)
122 def __delitem__(self, key):
123 del self._wrapped[key]
126 return [_wrap_element(el) for el in self._wrapped.elements()]
129 return [(attr, _wrap_element(el)) for attr, el in self._wrapped.items()]
133 return self._wrapped.keys
137 return self._wrapped.remove
141 return self._wrapped.add
145 return self._wrapped.dn
148 def dn(self, new_value):
149 self._wrapped.dn = new_value