]> git.notmuchmail.org Git - notmuch/blob - bindings/python/notmuch/database.py
python: whitespace fixed in docstrings
[notmuch] / bindings / python / notmuch / database.py
1 """
2 This file is part of notmuch.
3
4 Notmuch is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License as published by the
6 Free Software Foundation, either version 3 of the License, or (at your
7 option) any later version.
8
9 Notmuch is distributed in the hope that it will be useful, but WITHOUT
10 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with notmuch.  If not, see <http://www.gnu.org/licenses/>.
16
17 Copyright 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>'
18 """
19
20 import os
21 from ctypes import c_int, c_char_p, c_void_p, c_uint, c_long, byref
22 from notmuch.globals import (nmlib, STATUS, NotmuchError, NotInitializedError,
23      OutOfMemoryError, XapianError, Enum, _str)
24 from notmuch.thread import Threads
25 from notmuch.message import Messages, Message
26 from notmuch.tag import Tags
27
28 class Database(object):
29     """Represents a notmuch database (wraps notmuch_database_t)
30
31     .. note:: Do remember that as soon as we tear down this object,
32            all underlying derived objects such as queries, threads,
33            messages, tags etc will be freed by the underlying library
34            as well. Accessing these objects will lead to segfaults and
35            other unexpected behavior. See above for more details.
36     """
37     _std_db_path = None
38     """Class attribute to cache user's default database"""
39
40     MODE = Enum(['READ_ONLY', 'READ_WRITE'])
41     """Constants: Mode in which to open the database"""
42
43     """notmuch_database_get_directory"""
44     _get_directory = nmlib.notmuch_database_get_directory
45     _get_directory.restype = c_void_p
46
47     """notmuch_database_get_path"""
48     _get_path = nmlib.notmuch_database_get_path
49     _get_path.restype = c_char_p
50
51     """notmuch_database_get_version"""
52     _get_version = nmlib.notmuch_database_get_version
53     _get_version.restype = c_uint
54
55     """notmuch_database_open"""
56     _open = nmlib.notmuch_database_open
57     _open.restype = c_void_p
58
59     """notmuch_database_upgrade"""
60     _upgrade = nmlib.notmuch_database_upgrade
61     _upgrade.argtypes = [c_void_p, c_void_p, c_void_p]
62
63     """ notmuch_database_find_message"""
64     _find_message = nmlib.notmuch_database_find_message
65
66     """notmuch_database_find_message_by_filename"""
67     _find_message_by_filename = nmlib.notmuch_database_find_message_by_filename
68
69     """notmuch_database_get_all_tags"""
70     _get_all_tags = nmlib.notmuch_database_get_all_tags
71     _get_all_tags.restype = c_void_p
72
73     """notmuch_database_create"""
74     _create = nmlib.notmuch_database_create
75     _create.restype = c_void_p
76
77     def __init__(self, path=None, create=False, mode=0):
78         """If *path* is `None`, we will try to read a users notmuch
79         configuration and use his configured database. The location of the
80         configuration file can be specified through the environment variable
81         *NOTMUCH_CONFIG*, falling back to the default `~/.notmuch-config`.
82
83         If *create* is `True`, the database will always be created in
84         :attr:`MODE`.READ_WRITE mode. Default mode for opening is READ_ONLY.
85
86         :param path:   Directory to open/create the database in (see
87                        above for behavior if `None`)
88         :type path:    `str` or `None`
89         :param create: Pass `False` to open an existing, `True` to create a new
90                        database.
91         :type create:  bool
92         :param mode:   Mode to open a database in. Is always
93                        :attr:`MODE`.READ_WRITE when creating a new one.
94         :type mode:    :attr:`MODE`
95         :exception: :exc:`NotmuchError` or derived exception in case of
96             failure.
97         """
98         self._db = None
99         if path is None:
100             # no path specified. use a user's default database
101             if Database._std_db_path is None:
102                 #the following line throws a NotmuchError if it fails
103                 Database._std_db_path = self._get_user_default_db()
104             path = Database._std_db_path
105
106         if create == False:
107             self.open(path, mode)
108         else:
109             self.create(path)
110
111     def _assert_db_is_initialized(self):
112         """Raises :exc:`NotInitializedError` if self._db is `None`"""
113         if self._db is None:
114             raise NotInitializedError()
115
116     def create(self, path):
117         """Creates a new notmuch database
118
119         This function is used by __init__() and usually does not need
120         to be called directly. It wraps the underlying
121         *notmuch_database_create* function and creates a new notmuch
122         database at *path*. It will always return a database in :attr:`MODE`
123         .READ_WRITE mode as creating an empty database for
124         reading only does not make a great deal of sense.
125
126         :param path: A directory in which we should create the database.
127         :type path: str
128         :returns: Nothing
129         :exception: :exc:`NotmuchError` in case of any failure
130                     (possibly after printing an error message on stderr).
131         """
132         if self._db is not None:
133             raise NotmuchError(message="Cannot create db, this Database() "
134                                        "already has an open one.")
135
136         res = Database._create(_str(path), Database.MODE.READ_WRITE)
137
138         if res is None:
139             raise NotmuchError(
140                 message="Could not create the specified database")
141         self._db = res
142
143     def open(self, path, mode=0):
144         """Opens an existing database
145
146         This function is used by __init__() and usually does not need
147         to be called directly. It wraps the underlying
148         *notmuch_database_open* function.
149
150         :param status: Open the database in read-only or read-write mode
151         :type status:  :attr:`MODE`
152         :returns: Nothing
153         :exception: Raises :exc:`NotmuchError` in case
154                     of any failure (after printing an error message on stderr).
155         """
156         res = Database._open(_str(path), mode)
157
158         if res is None:
159             raise NotmuchError(message="Could not open the specified database")
160         self._db = res
161
162     def get_path(self):
163         """Returns the file path of an open database
164
165         .. ..:: Wraps underlying `notmuch_database_get_path`"""
166         self._assert_db_is_initialized()
167         return Database._get_path(self._db).decode('utf-8')
168
169     def get_version(self):
170         """Returns the database format version
171
172         :returns: The database version as positive integer
173         :exception: :exc:`NotInitializedError` if
174                     the database was not intitialized.
175         """
176         self._assert_db_is_initialized()
177         return Database._get_version(self._db)
178
179     def needs_upgrade(self):
180         """Does this database need to be upgraded before writing to it?
181
182         If this function returns `True` then no functions that modify the
183         database (:meth:`add_message`,
184         :meth:`Message.add_tag`, :meth:`Directory.set_mtime`,
185         etc.) will work unless :meth:`upgrade` is called successfully first.
186
187         :returns: `True` or `False`
188         :exception: :exc:`NotInitializedError` if
189                     the database was not intitialized.
190         """
191         self._assert_db_is_initialized()
192         return nmlib.notmuch_database_needs_upgrade(self._db)
193
194     def upgrade(self):
195         """Upgrades the current database
196
197         After opening a database in read-write mode, the client should
198         check if an upgrade is needed (notmuch_database_needs_upgrade) and
199         if so, upgrade with this function before making any modifications.
200
201         NOT IMPLEMENTED: The optional progress_notify callback can be
202         used by the caller to provide progress indication to the
203         user. If non-NULL it will be called periodically with
204         'progress' as a floating-point value in the range of [0.0..1.0]
205         indicating the progress made so far in the upgrade process.
206
207         :TODO: catch exceptions, document return values and etc...
208
209         :exception: :exc:`NotInitializedError` if
210                     the database was not intitialized.
211         """
212         self._assert_db_is_initialized()
213         status = Database._upgrade(self._db, None, None)
214         #TODO: catch exceptions, document return values and etc
215         return status
216
217     def begin_atomic(self):
218         """Begin an atomic database operation
219
220         Any modifications performed between a successful
221         :meth:`begin_atomic` and a :meth:`end_atomic` will be applied to
222         the database atomically.  Note that, unlike a typical database
223         transaction, this only ensures atomicity, not durability;
224         neither begin nor end necessarily flush modifications to disk.
225
226         :returns: :attr:`STATUS`.SUCCESS or raises
227
228         :exception: :exc:`NotmuchError`:
229             :attr:`STATUS`.XAPIAN_EXCEPTION
230                 Xapian exception occurred; atomic section not entered.
231
232             :exc:`NotInitializedError` if
233                 the database was not intitialized.
234
235         *Added in notmuch 0.9*"""
236         self._assert_db_is_initialized()
237         status = nmlib.notmuch_database_begin_atomic(self._db)
238         if status != STATUS.SUCCESS:
239             raise NotmuchError(status)
240         return status
241
242     def end_atomic(self):
243         """Indicate the end of an atomic database operation
244
245         See :meth:`begin_atomic` for details.
246
247         :returns: :attr:`STATUS`.SUCCESS or raises
248
249         :exception:
250             :exc:`NotmuchError`:
251                 :attr:`STATUS`.XAPIAN_EXCEPTION
252                     A Xapian exception occurred; atomic section not
253                     ended.
254                 :attr:`STATUS`.UNBALANCED_ATOMIC:
255                     end_atomic has been called more times than begin_atomic.
256
257             :exc:`NotInitializedError` if
258                     the database was not intitialized.
259
260         *Added in notmuch 0.9*"""
261         self._assert_db_is_initialized()
262         status = nmlib.notmuch_database_end_atomic(self._db)
263         if status != STATUS.SUCCESS:
264             raise NotmuchError(status)
265         return status
266
267     def get_directory(self, path):
268         """Returns a :class:`Directory` of path,
269         (creating it if it does not exist(?))
270
271         .. warning:: This call needs a writeable database in
272            :attr:`Database.MODE`.READ_WRITE mode. The underlying library will exit the
273            program if this method is used on a read-only database!
274
275         :param path: An unicode string containing the path relative to the path
276               of database (see :meth:`get_path`), or else should be an absolute path
277               with initial components that match the path of 'database'.
278         :returns: :class:`Directory` or raises an exception.
279         :exception:
280             :exc:`NotmuchError` with :attr:`STATUS`.FILE_ERROR
281                     If path is not relative database or absolute with initial
282                     components same as database.
283
284             :exc:`NotInitializedError` if
285                     the database was not intitialized.
286         """
287         self._assert_db_is_initialized()
288         # sanity checking if path is valid, and make path absolute
289         if path[0] == os.sep:
290             # we got an absolute path
291             if not path.startswith(self.get_path()):
292                 # but its initial components are not equal to the db path
293                 raise NotmuchError(STATUS.FILE_ERROR,
294                                    message="Database().get_directory() called "
295                                            "with a wrong absolute path.")
296             abs_dirpath = path
297         else:
298             #we got a relative path, make it absolute
299             abs_dirpath = os.path.abspath(os.path.join(self.get_path(), path))
300
301         dir_p = Database._get_directory(self._db, _str(path))
302
303         # return the Directory, init it with the absolute path
304         return Directory(_str(abs_dirpath), dir_p, self)
305
306     def add_message(self, filename, sync_maildir_flags=False):
307         """Adds a new message to the database
308
309         :param filename: should be a path relative to the path of the
310             open database (see :meth:`get_path`), or else should be an
311             absolute filename with initial components that match the
312             path of the database.
313
314             The file should be a single mail message (not a
315             multi-message mbox) that is expected to remain at its
316             current location, since the notmuch database will reference
317             the filename, and will not copy the entire contents of the
318             file.
319
320         :param sync_maildir_flags: If the message contains Maildir
321             flags, we will -depending on the notmuch configuration- sync
322             those tags to initial notmuch tags, if set to `True`. It is
323             `False` by default to remain consistent with the libnotmuch
324             API. You might want to look into the underlying method
325             :meth:`Message.maildir_flags_to_tags`.
326
327         :returns: On success, we return
328
329            1) a :class:`Message` object that can be used for things
330               such as adding tags to the just-added message.
331            2) one of the following :attr:`STATUS` values:
332
333               :attr:`STATUS`.SUCCESS
334                   Message successfully added to database.
335               :attr:`STATUS`.DUPLICATE_MESSAGE_ID
336                   Message has the same message ID as another message already
337                   in the database. The new filename was successfully added
338                   to the list of the filenames for the existing message.
339
340         :rtype:   2-tuple(:class:`Message`, :attr:`STATUS`)
341
342         :exception: Raises a :exc:`NotmuchError` with the following meaning.
343               If such an exception occurs, nothing was added to the database.
344
345               :attr:`STATUS`.FILE_ERROR
346                       An error occurred trying to open the file, (such as
347                       permission denied, or file not found, etc.).
348               :attr:`STATUS`.FILE_NOT_EMAIL
349                       The contents of filename don't look like an email
350                       message.
351               :attr:`STATUS`.READ_ONLY_DATABASE
352                       Database was opened in read-only mode so no message can
353                       be added.
354
355             :exc:`NotInitializedError` if
356                     the database was not intitialized.
357         """
358         self._assert_db_is_initialized()
359         msg_p = c_void_p()
360         status = nmlib.notmuch_database_add_message(self._db,
361                                                   _str(filename),
362                                                   byref(msg_p))
363
364         if not status in [STATUS.SUCCESS, STATUS.DUPLICATE_MESSAGE_ID]:
365             raise NotmuchError(status)
366
367         #construct Message() and return
368         msg = Message(msg_p, self)
369         #automatic sync initial tags from Maildir flags
370         if sync_maildir_flags:
371             msg.maildir_flags_to_tags()
372         return (msg, status)
373
374     def remove_message(self, filename):
375         """Removes a message (filename) from the given notmuch database
376
377         Note that only this particular filename association is removed from
378         the database. If the same message (as determined by the message ID)
379         is still available via other filenames, then the message will
380         persist in the database for those filenames. When the last filename
381         is removed for a particular message, the database content for that
382         message will be entirely removed.
383
384         :returns: A :attr:`STATUS` value with the following meaning:
385
386              :attr:`STATUS`.SUCCESS
387                The last filename was removed and the message was removed
388                from the database.
389              :attr:`STATUS`.DUPLICATE_MESSAGE_ID
390                This filename was removed but the message persists in the
391                database with at least one other filename.
392
393         :exception: Raises a :exc:`NotmuchError` with the following meaning.
394              If such an exception occurs, nothing was removed from the
395              database.
396
397              :attr:`STATUS`.READ_ONLY_DATABASE
398                Database was opened in read-only mode so no message can be
399                removed.
400
401              :exc:`NotInitializedError` if
402                     the database was not intitialized.
403         """
404         self._assert_db_is_initialized()
405         return nmlib.notmuch_database_remove_message(self._db,
406                                                        filename)
407
408     def find_message(self, msgid):
409         """Returns a :class:`Message` as identified by its message ID
410
411         Wraps the underlying *notmuch_database_find_message* function.
412
413         :param msgid: The message ID
414         :type msgid: unicode or str
415         :returns: :class:`Message` or `None` if no message is found.
416         :exception:
417             :exc:`OutOfMemoryError`
418                   If an Out-of-memory occured while constructing the message.
419             :exc:`XapianError`
420                   In case of a Xapian Exception. These exceptions
421                   include "Database modified" situations, e.g. when the
422                   notmuch database has been modified by another program
423                   in the meantime. In this case, you should close and
424                   reopen the database and retry.
425             :exc:`NotInitializedError` if
426                     the database was not intitialized.
427         """
428         self._assert_db_is_initialized()
429         msg_p = c_void_p()
430         status = Database._find_message(self._db, _str(msgid), byref(msg_p))
431         if status != STATUS.SUCCESS:
432             raise NotmuchError(status)
433         return msg_p and Message(msg_p, self) or None
434
435     def find_message_by_filename(self, filename):
436         """Find a message with the given filename
437
438         .. warning:: This call needs a writeable database in
439            :attr:`Database.MODE`.READ_WRITE mode. The underlying library will
440            exit the program if this method is used on a read-only
441            database!
442
443         :returns: If the database contains a message with the given
444             filename, then a class:`Message:` is returned.  This
445             function returns None if no message is found with the given
446             filename.
447
448         :exception:
449             :exc:`OutOfMemoryError`
450                   If an Out-of-memory occured while constructing the message.
451             :exc:`XapianError`
452                   In case of a Xapian Exception. These exceptions
453                   include "Database modified" situations, e.g. when the
454                   notmuch database has been modified by another program
455                   in the meantime. In this case, you should close and
456                   reopen the database and retry.
457             :exc:`NotInitializedError` if
458                     the database was not intitialized.
459
460         *Added in notmuch 0.9*"""
461         self._assert_db_is_initialized()
462         msg_p = c_void_p()
463         status = Database._find_message_by_filename(self._db, _str(filename),
464                                                     byref(msg_p))
465         if status != STATUS.SUCCESS:
466             raise NotmuchError(status)
467         return msg_p and Message(msg_p, self) or None
468
469     def get_all_tags(self):
470         """Returns :class:`Tags` with a list of all tags found in the database
471
472         :returns: :class:`Tags`
473         :execption: :exc:`NotmuchError` with :attr:`STATUS`.NULL_POINTER on error
474         """
475         self._assert_db_is_initialized()
476         tags_p = Database._get_all_tags(self._db)
477         if tags_p == None:
478             raise NotmuchError(STATUS.NULL_POINTER)
479         return Tags(tags_p, self)
480
481     def create_query(self, querystring):
482         """Returns a :class:`Query` derived from this database
483
484         This is a shorthand method for doing::
485
486           # short version
487           # Automatically frees the Database() when 'q' is deleted
488
489           q  = Database(dbpath).create_query('from:"Biene Maja"')
490
491           # long version, which is functionally equivalent but will keep the
492           # Database in the 'db' variable around after we delete 'q':
493
494           db = Database(dbpath)
495           q  = Query(db,'from:"Biene Maja"')
496
497         This function is a python extension and not in the underlying C API.
498         """
499         self._assert_db_is_initialized()
500         return Query(self, querystring)
501
502     def __repr__(self):
503         return "'Notmuch DB " + self.get_path() + "'"
504
505     def __del__(self):
506         """Close and free the notmuch database if needed"""
507         if self._db is not None:
508             nmlib.notmuch_database_close(self._db)
509
510     def _get_user_default_db(self):
511         """ Reads a user's notmuch config and returns his db location
512
513         Throws a NotmuchError if it cannot find it"""
514         from ConfigParser import SafeConfigParser
515         config = SafeConfigParser()
516         conf_f = os.getenv('NOTMUCH_CONFIG',
517                            os.path.expanduser('~/.notmuch-config'))
518         config.read(conf_f)
519         if not config.has_option('database', 'path'):
520             raise NotmuchError(message="No DB path specified"
521                                        " and no user default found")
522         return config.get('database', 'path').decode('utf-8')
523
524     @property
525     def db_p(self):
526         """Property returning a pointer to `notmuch_database_t` or `None`
527
528         This should normally not be needed by a user (and is not yet
529         guaranteed to remain stable in future versions).
530         """
531         return self._db
532
533
534 class Query(object):
535     """Represents a search query on an opened :class:`Database`.
536
537     A query selects and filters a subset of messages from the notmuch
538     database we derive from.
539
540     Query() provides an instance attribute :attr:`sort`, which
541     contains the sort order (if specified via :meth:`set_sort`) or
542     `None`.
543
544     Technically, it wraps the underlying *notmuch_query_t* struct.
545
546     .. note:: Do remember that as soon as we tear down this object,
547            all underlying derived objects such as threads,
548            messages, tags etc will be freed by the underlying library
549            as well. Accessing these objects will lead to segfaults and
550            other unexpected behavior. See above for more details.
551     """
552     # constants
553     SORT = Enum(['OLDEST_FIRST', 'NEWEST_FIRST', 'MESSAGE_ID', 'UNSORTED'])
554     """Constants: Sort order in which to return results"""
555
556     """notmuch_query_create"""
557     _create = nmlib.notmuch_query_create
558     _create.restype = c_void_p
559
560     """notmuch_query_search_threads"""
561     _search_threads = nmlib.notmuch_query_search_threads
562     _search_threads.restype = c_void_p
563
564     """notmuch_query_search_messages"""
565     _search_messages = nmlib.notmuch_query_search_messages
566     _search_messages.restype = c_void_p
567
568     """notmuch_query_count_messages"""
569     _count_messages = nmlib.notmuch_query_count_messages
570     _count_messages.restype = c_uint
571
572     def __init__(self, db, querystr):
573         """
574         :param db: An open database which we derive the Query from.
575         :type db: :class:`Database`
576         :param querystr: The query string for the message.
577         :type querystr: utf-8 encoded str or unicode
578         """
579         self._db = None
580         self._query = None
581         self.sort = None
582         self.create(db, querystr)
583
584     def create(self, db, querystr):
585         """Creates a new query derived from a Database
586
587         This function is utilized by __init__() and usually does not need to
588         be called directly.
589
590         :param db: Database to create the query from.
591         :type db: :class:`Database`
592         :param querystr: The query string
593         :type querystr: utf-8 encoded str or unicode
594         :returns: Nothing
595         :exception: :exc:`NotmuchError`
596
597                       * :attr:`STATUS`.NOT_INITIALIZED if db is not inited
598                       * :attr:`STATUS`.NULL_POINTER if the query creation failed
599                         (too little memory)
600         """
601         if db.db_p is None:
602             raise NotmuchError(STATUS.NOT_INITIALIZED)
603         # create reference to parent db to keep it alive
604         self._db = db
605         # create query, return None if too little mem available
606         query_p = Query._create(db.db_p, _str(querystr))
607         if query_p is None:
608             raise NotmuchError(STATUS.NULL_POINTER)
609         self._query = query_p
610
611     def set_sort(self, sort):
612         """Set the sort order future results will be delivered in
613
614         Wraps the underlying *notmuch_query_set_sort* function.
615
616         :param sort: Sort order (see :attr:`Query.SORT`)
617         :returns: Nothing
618         :exception: :exc:`NotmuchError` :attr:`STATUS`.NOT_INITIALIZED if query has not
619                     been initialized.
620         """
621         if self._query is None:
622             raise NotmuchError(STATUS.NOT_INITIALIZED)
623
624         self.sort = sort
625         nmlib.notmuch_query_set_sort(self._query, sort)
626
627     def search_threads(self):
628         """Execute a query for threads
629
630         Execute a query for threads, returning a :class:`Threads` iterator.
631         The returned threads are owned by the query and as such, will only be
632         valid until the Query is deleted.
633
634         The method sets :attr:`Message.FLAG`\.MATCH for those messages that
635         match the query. The method :meth:`Message.get_flag` allows us
636         to get the value of this flag.
637
638         Technically, it wraps the underlying
639         *notmuch_query_search_threads* function.
640
641         :returns: :class:`Threads`
642         :exception: :exc:`NotmuchError`
643
644                       * :attr:`STATUS`.NOT_INITIALIZED if query is not inited
645                       * :attr:`STATUS`.NULL_POINTER if search_threads failed
646         """
647         if self._query is None:
648             raise NotmuchError(STATUS.NOT_INITIALIZED)
649
650         threads_p = Query._search_threads(self._query)
651
652         if threads_p is None:
653             raise NotmuchError(STATUS.NULL_POINTER)
654
655         return Threads(threads_p, self)
656
657     def search_messages(self):
658         """Filter messages according to the query and return
659         :class:`Messages` in the defined sort order
660
661         Technically, it wraps the underlying
662         *notmuch_query_search_messages* function.
663
664         :returns: :class:`Messages`
665         :exception: :exc:`NotmuchError`
666
667                       * :attr:`STATUS`.NOT_INITIALIZED if query is not inited
668                       * :attr:`STATUS`.NULL_POINTER if search_messages failed
669         """
670         if self._query is None:
671             raise NotmuchError(STATUS.NOT_INITIALIZED)
672
673         msgs_p = Query._search_messages(self._query)
674
675         if msgs_p is None:
676             raise NotmuchError(STATUS.NULL_POINTER)
677
678         return Messages(msgs_p, self)
679
680     def count_messages(self):
681         """Estimate the number of messages matching the query
682
683         This function performs a search and returns Xapian's best
684         guess as to the number of matching messages. It is much faster
685         than performing :meth:`search_messages` and counting the
686         result with `len()` (although it always returned the same
687         result in my tests). Technically, it wraps the underlying
688         *notmuch_query_count_messages* function.
689
690         :returns: :class:`Messages`
691         :exception: :exc:`NotmuchError`
692
693                       * :attr:`STATUS`.NOT_INITIALIZED if query is not inited
694         """
695         if self._query is None:
696             raise NotmuchError(STATUS.NOT_INITIALIZED)
697
698         return Query._count_messages(self._query)
699
700     def __del__(self):
701         """Close and free the Query"""
702         if self._query is not None:
703             nmlib.notmuch_query_destroy(self._query)
704
705
706 class Directory(object):
707     """Represents a directory entry in the notmuch directory
708
709     Modifying attributes of this object will modify the
710     database, not the real directory attributes.
711
712     The Directory object is usually derived from another object
713     e.g. via :meth:`Database.get_directory`, and will automatically be
714     become invalid whenever that parent is deleted. You should
715     therefore initialized this object handing it a reference to the
716     parent, preventing the parent from automatically being garbage
717     collected.
718     """
719
720     """notmuch_directory_get_mtime"""
721     _get_mtime = nmlib.notmuch_directory_get_mtime
722     _get_mtime.restype = c_long
723
724     """notmuch_directory_set_mtime"""
725     _set_mtime = nmlib.notmuch_directory_set_mtime
726     _set_mtime.argtypes = [c_char_p, c_long]
727
728     """notmuch_directory_get_child_files"""
729     _get_child_files = nmlib.notmuch_directory_get_child_files
730     _get_child_files.restype = c_void_p
731
732     """notmuch_directory_get_child_directories"""
733     _get_child_directories = nmlib.notmuch_directory_get_child_directories
734     _get_child_directories.restype = c_void_p
735
736     def _assert_dir_is_initialized(self):
737         """Raises a NotmuchError(:attr:`STATUS`.NOT_INITIALIZED) if dir_p is None"""
738         if self._dir_p is None:
739             raise NotmuchError(STATUS.NOT_INITIALIZED)
740
741     def __init__(self, path, dir_p, parent):
742         """
743         :param path:   The absolute path of the directory object as unicode.
744         :param dir_p:  The pointer to an internal notmuch_directory_t object.
745         :param parent: The object this Directory is derived from
746                        (usually a :class:`Database`). We do not directly use
747                        this, but store a reference to it as long as
748                        this Directory object lives. This keeps the
749                        parent object alive.
750         """
751         assert isinstance(path, unicode), "Path needs to be an UNICODE object"
752         self._path = path
753         self._dir_p = dir_p
754         self._parent = parent
755
756     def set_mtime(self, mtime):
757         """Sets the mtime value of this directory in the database
758
759         The intention is for the caller to use the mtime to allow efficient
760         identification of new messages to be added to the database. The
761         recommended usage is as follows:
762
763         * Read the mtime of a directory from the filesystem
764
765         * Call :meth:`Database.add_message` for all mail files in
766           the directory
767
768         * Call notmuch_directory_set_mtime with the mtime read from the
769           filesystem.  Then, when wanting to check for updates to the
770           directory in the future, the client can call :meth:`get_mtime`
771           and know that it only needs to add files if the mtime of the
772           directory and files are newer than the stored timestamp.
773
774           .. note:: :meth:`get_mtime` function does not allow the caller
775                  to distinguish a timestamp of 0 from a non-existent
776                  timestamp. So don't store a timestamp of 0 unless you are
777                  comfortable with that.
778
779           :param mtime: A (time_t) timestamp
780           :returns: Nothing on success, raising an exception on failure.
781           :exception: :exc:`NotmuchError`:
782
783                         :attr:`STATUS`.XAPIAN_EXCEPTION
784                           A Xapian exception occurred, mtime not stored.
785                         :attr:`STATUS`.READ_ONLY_DATABASE
786                           Database was opened in read-only mode so directory
787                           mtime cannot be modified.
788                         :attr:`STATUS`.NOT_INITIALIZED
789                           The directory has not been initialized
790         """
791         self._assert_dir_is_initialized()
792         #TODO: make sure, we convert the mtime parameter to a 'c_long'
793         status = Directory._set_mtime(self._dir_p, mtime)
794
795         #return on success
796         if status == STATUS.SUCCESS:
797             return
798         #fail with Exception otherwise
799         raise NotmuchError(status)
800
801     def get_mtime(self):
802         """Gets the mtime value of this directory in the database
803
804         Retrieves a previously stored mtime for this directory.
805
806         :param mtime: A (time_t) timestamp
807         :returns: Nothing on success, raising an exception on failure.
808         :exception: :exc:`NotmuchError`:
809
810                         :attr:`STATUS`.NOT_INITIALIZED
811                           The directory has not been initialized
812         """
813         self._assert_dir_is_initialized()
814         return Directory._get_mtime(self._dir_p)
815
816     # Make mtime attribute a property of Directory()
817     mtime = property(get_mtime, set_mtime, doc="""Property that allows getting
818                      and setting of the Directory *mtime* (read-write)
819
820                      See :meth:`get_mtime` and :meth:`set_mtime` for usage and
821                      possible exceptions.""")
822
823     def get_child_files(self):
824         """Gets a Filenames iterator listing all the filenames of
825         messages in the database within the given directory.
826
827         The returned filenames will be the basename-entries only (not
828         complete paths.
829         """
830         self._assert_dir_is_initialized()
831         files_p = Directory._get_child_files(self._dir_p)
832         return Filenames(files_p, self)
833
834     def get_child_directories(self):
835         """Gets a :class:`Filenames` iterator listing all the filenames of
836         sub-directories in the database within the given directory
837
838         The returned filenames will be the basename-entries only (not
839         complete paths.
840         """
841         self._assert_dir_is_initialized()
842         files_p = Directory._get_child_directories(self._dir_p)
843         return Filenames(files_p, self)
844
845     @property
846     def path(self):
847         """Returns the absolute path of this Directory (read-only)"""
848         return self._path
849
850     def __repr__(self):
851         """Object representation"""
852         return "<notmuch Directory object '%s'>" % self._path
853
854     def __del__(self):
855         """Close and free the Directory"""
856         if self._dir_p is not None:
857             nmlib.notmuch_directory_destroy(self._dir_p)
858
859
860 class Filenames(object):
861     """An iterator over File- or Directory names stored in the database"""
862
863     #notmuch_filenames_get
864     _get = nmlib.notmuch_filenames_get
865     _get.restype = c_char_p
866
867     def __init__(self, files_p, parent):
868         """
869         :param files_p: The pointer to an internal notmuch_filenames_t object.
870         :param parent: The object this Directory is derived from
871                        (usually a Directory()). We do not directly use
872                        this, but store a reference to it as long as
873                        this Directory object lives. This keeps the
874                        parent object alive.
875         """
876         self._files_p = files_p
877         self._parent = parent
878
879     def __iter__(self):
880         """ Make Filenames an iterator """
881         return self
882
883     def next(self):
884         if self._files_p is None:
885             raise NotmuchError(STATUS.NOT_INITIALIZED)
886
887         if not nmlib.notmuch_filenames_valid(self._files_p):
888             self._files_p = None
889             raise StopIteration
890
891         file = Filenames._get(self._files_p)
892         nmlib.notmuch_filenames_move_to_next(self._files_p)
893         return file
894
895     def __len__(self):
896         """len(:class:`Filenames`) returns the number of contained files
897
898         .. note:: As this iterates over the files, we will not be able to
899                iterate over them again! So this will fail::
900
901                  #THIS FAILS
902                  files = Database().get_directory('').get_child_files()
903                  if len(files) > 0:              #this 'exhausts' msgs
904                      # next line raises NotmuchError(:attr:`STATUS`.NOT_INITIALIZED)!!!
905                      for file in files: print file
906         """
907         if self._files_p is None:
908             raise NotmuchError(STATUS.NOT_INITIALIZED)
909
910         i = 0
911         while nmlib.notmuch_filenames_valid(self._files_p):
912             nmlib.notmuch_filenames_move_to_next(self._files_p)
913             i += 1
914         self._files_p = None
915         return i
916
917     def __del__(self):
918         """Close and free Filenames"""
919         if self._files_p is not None:
920             nmlib.notmuch_filenames_destroy(self._files_p)