]> git.notmuchmail.org Git - notmuch/blob - bindings/python/notmuch/compat.py
Merge branch 'release'
[notmuch] / bindings / python / notmuch / compat.py
1 '''
2 This file is part of notmuch.
3
4 This module handles differences between python2.x and python3.x and
5 allows the notmuch bindings to support both version families with one
6 source tree.
7
8 Notmuch is free software: you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the
10 Free Software Foundation, either version 3 of the License, or (at your
11 option) any later version.
12
13 Notmuch is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with notmuch.  If not, see <https://www.gnu.org/licenses/>.
20
21 Copyright 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>
22 Copyright 2012 Justus Winter <4winter@informatik.uni-hamburg.de>
23 '''
24
25 import sys
26
27 if sys.version_info[0] == 2:
28     from ConfigParser import SafeConfigParser
29
30     class Python3StringMixIn(object):
31         def __str__(self):
32             return unicode(self).encode('utf-8')
33
34     def encode_utf8(value):
35         '''
36         Ensure a nicely utf-8 encoded string to pass to wrapped
37         libnotmuch functions.
38
39         C++ code expects strings to be well formatted and unicode
40         strings to have no null bytes.
41         '''
42         if not isinstance(value, basestring):
43             raise TypeError('Expected str or unicode, got %s' % type(value))
44
45         if isinstance(value, unicode):
46             return value.encode('utf-8', 'replace')
47
48         return value
49 else:
50     from configparser import SafeConfigParser
51
52     class Python3StringMixIn(object):
53         def __str__(self):
54             return self.__unicode__()
55
56     def encode_utf8(value):
57         '''
58         Ensure a nicely utf-8 encoded string to pass to wrapped
59         libnotmuch functions.
60
61         C++ code expects strings to be well formatted and unicode
62         strings to have no null bytes.
63         '''
64         if not isinstance(value, str):
65             raise TypeError('Expected str, got %s' % type(value))
66
67         return value.encode('utf-8', 'replace')
68
69 # We import the SafeConfigParser class on behalf of other code to cope
70 # with the differences between Python 2 and 3.
71 SafeConfigParser # avoid warning about unused import