1 # Text wrapper for ldb bindings
3 # Copyright (C) 2015 Petr Viktorin <pviktori@redhat.com>
4 # Published under the GNU LGPLv3 or later
9 def _recursive_encode(obj
):
10 if isinstance(obj
, bytes
):
12 elif isinstance(obj
, str):
13 return obj
.encode('utf-8')
15 return [_recursive_encode(o
) for o
in obj
]
18 class _WrapBase(object):
21 def _wrap(cls
, wrapped
):
22 self
= cls
.__new
__(cls
)
23 self
._wrapped
= wrapped
27 return len(self
._wrapped
)
29 def __eq__(self
, other
):
30 if hasattr(other
, '_wrapped'):
31 return self
._wrapped
== other
._wrapped
33 return self
._wrapped
== other
35 def __ne__(self
, other
):
36 if hasattr(other
, '_wrapped'):
37 return self
._wrapped
!= other
._wrapped
39 return self
._wrapped
!= other
41 def __lt__(self
, other
):
42 if hasattr(other
, '_wrapped'):
43 return self
._wrapped
< other
._wrapped
45 return self
._wrapped
< other
47 def __le__(self
, other
):
48 if hasattr(other
, '_wrapped'):
49 return self
._wrapped
>= other
._wrapped
51 return self
._wrapped
>= other
53 def __gt__(self
, other
):
54 if hasattr(other
, '_wrapped'):
55 return self
._wrapped
> other
._wrapped
57 return self
._wrapped
> other
59 def __ge__(self
, other
):
60 if hasattr(other
, '_wrapped'):
61 return self
._wrapped
>= other
._wrapped
63 return self
._wrapped
>= other
66 return '%s.text' % repr(self
._wrapped
)
69 class MessageElementTextWrapper(_WrapBase
):
71 """Text interface for a LDB message element"""
74 for item
in self
._wrapped
:
75 yield item
.decode('utf-8')
77 def __getitem__(self
, key
):
78 result
= self
._wrapped
[key
]
82 return result
.decode('utf-8')
86 return self
._wrapped
.flags
90 return self
._wrapped
.set_flags
93 _wrap_element
= MessageElementTextWrapper
._wrap
96 class MessageTextWrapper(_WrapBase
):
98 """Text interface for a LDB message"""
100 def __getitem__(self
, key
):
101 result
= self
._wrapped
[key
]
105 return _wrap_element(result
)
107 def get(self
, *args
, **kwargs
):
108 result
= self
._wrapped
.get(*args
, **kwargs
)
109 if isinstance(result
, ldb
.MessageElement
):
110 return _wrap_element(result
)
111 elif isinstance(result
, bytes
):
112 return result
.decode('utf-8')
116 def __setitem__(self
, key
, item
):
117 self
._wrapped
[key
] = _recursive_encode(item
)
119 def __delitem__(self
, key
):
120 del self
._wrapped
[key
]
123 return [_wrap_element(el
) for el
in self
._wrapped
.elements()]
126 return [(attr
, _wrap_element(el
)) for attr
, el
in self
._wrapped
.items()]
130 return self
._wrapped
.keys
134 return self
._wrapped
.remove
138 return self
._wrapped
.add
142 return self
._wrapped
.dn
145 def dn(self
, new_value
):
146 self
._wrapped
.dn
= new_value