]> git.notmuchmail.org Git - notmuch/blob - cnotmuch/globals.py
Implement an Enum class and make the STATUS object one
[notmuch] / cnotmuch / globals.py
1 from ctypes import CDLL, c_char_p, c_int
2 from ctypes.util import find_library
3
4 #-----------------------------------------------------------------------------
5 #package-global instance of the notmuch library
6 #TODO: lazy load this on first access?
7 so = find_library('notmuch')
8 if so is None:
9   raise ImportError("Could not find shared 'notmuch' library.")
10 nmlib = CDLL(so)
11 #-----------------------------------------------------------------------------
12 class Enum(object):
13   """Provides ENUMS as "code=Enum(['a','b','c'])" where code.a=0 etc..."""
14   def __init__(self, names):
15     for number, name in enumerate(names):
16       setattr(self, name, number)
17
18 #-----------------------------------------------------------------------------
19 class Status(Enum):
20     """Enum with a string representation of a notmuch_status_t value."""
21     __name__="foo"
22     _status2str = nmlib.notmuch_status_to_string
23     _status2str.restype = c_char_p
24     _status2str.argtypes = [c_int]
25
26     def __init__(self, statuslist):
27         """It is initialized with a list of strings that are available as
28         Status().string1 - Status().stringn attributes.
29         """
30         super(Status, self).__init__(statuslist)
31
32     def status2str(self, status):
33         """Get a string representation of a notmuch_status_t value."""   
34         # define strings for custom error messages
35         if status == STATUS.NOT_INITIALIZED:
36           return "Operation on uninitialized object impossible."
37         return str(Status._status2str(status))
38
39 STATUS = Status(['SUCCESS',
40   'OUT_OF_MEMORY',
41   'READ_ONLY_DATABASE',
42   'XAPIAN_EXCEPTION',
43   'FILE_ERROR',
44   'FILE_NOT_EMAIL',
45   'DUPLICATE_MESSAGE_ID',
46   'NULL_POINTER',
47   'TAG_TOO_LONG',
48   'UNBALANCED_FREEZE_THAW',
49   'NOT_INITIALIZED'])
50
51
52 class NotmuchError(Exception):
53     def __init__(self, status=None, message=None):
54         """Is initiated with a (notmuch.STATUS[,message=None])"""
55         super(NotmuchError, self).__init__(message, status)
56
57     def __str__(self):
58         if self.args[0] is not None: return self.args[0]
59         else: return STATUS.status2str(self.args[1])
60