2 This file is part of notmuch.
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.
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
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/>.
17 Copyright 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>'
21 from ctypes import c_char_p, c_void_p, c_uint, c_long, byref, POINTER
22 from notmuch.globals import (nmlib, STATUS, NotmuchError, NotInitializedError,
23 NullPointerError, Enum, _str,
24 NotmuchDatabaseP, NotmuchDirectoryP, NotmuchMessageP, NotmuchTagsP,
25 NotmuchQueryP, NotmuchMessagesP, NotmuchThreadsP, NotmuchFilenamesP)
26 from notmuch.thread import Threads
27 from notmuch.message import Messages, Message
28 from notmuch.tag import Tags
31 class Database(object):
32 """The :class:`Database` is the highest-level object that notmuch
33 provides. It references a notmuch database, and can be opened in
34 read-only or read-write mode. A :class:`Query` can be derived from
35 or be applied to a specific database to find messages. Also adding
36 and removing messages to the database happens via this
37 object. Modifications to the database are not atmic by default (see
38 :meth:`begin_atomic`) and once a database has been modified, all
39 other database objects pointing to the same data-base will throw an
40 :exc:`XapianError` as the underlying database has been
41 modified. Close and reopen the database to continue working with it.
45 Any function in this class can and will throw an
46 :exc:`NotInitializedError` if the database was not intitialized
51 Do remember that as soon as we tear down (e.g. via `del db`) this
52 object, all underlying derived objects such as queries, threads,
53 messages, tags etc will be freed by the underlying library as well.
54 Accessing these objects will lead to segfaults and other unexpected
55 behavior. See above for more details.
58 """Class attribute to cache user's default database"""
60 MODE = Enum(['READ_ONLY', 'READ_WRITE'])
61 """Constants: Mode in which to open the database"""
63 """notmuch_database_get_directory"""
64 _get_directory = nmlib.notmuch_database_get_directory
65 _get_directory.argtypes = [NotmuchDatabaseP, c_char_p]
66 _get_directory.restype = NotmuchDirectoryP
68 """notmuch_database_get_path"""
69 _get_path = nmlib.notmuch_database_get_path
70 _get_path.argtypes = [NotmuchDatabaseP]
71 _get_path.restype = c_char_p
73 """notmuch_database_get_version"""
74 _get_version = nmlib.notmuch_database_get_version
75 _get_version.argtypes = [NotmuchDatabaseP]
76 _get_version.restype = c_uint
78 """notmuch_database_open"""
79 _open = nmlib.notmuch_database_open
80 _open.argtypes = [c_char_p, c_uint]
81 _open.restype = NotmuchDatabaseP
83 """notmuch_database_upgrade"""
84 _upgrade = nmlib.notmuch_database_upgrade
85 _upgrade.argtypes = [NotmuchDatabaseP, c_void_p, c_void_p]
86 _upgrade.restype = c_uint
88 """ notmuch_database_find_message"""
89 _find_message = nmlib.notmuch_database_find_message
90 _find_message.argtypes = [NotmuchDatabaseP, c_char_p,
91 POINTER(NotmuchMessageP)]
92 _find_message.restype = c_uint
94 """notmuch_database_find_message_by_filename"""
95 _find_message_by_filename = nmlib.notmuch_database_find_message_by_filename
96 _find_message_by_filename.argtypes = [NotmuchDatabaseP, c_char_p,
97 POINTER(NotmuchMessageP)]
98 _find_message_by_filename.restype = c_uint
100 """notmuch_database_get_all_tags"""
101 _get_all_tags = nmlib.notmuch_database_get_all_tags
102 _get_all_tags.argtypes = [NotmuchDatabaseP]
103 _get_all_tags.restype = NotmuchTagsP
105 """notmuch_database_create"""
106 _create = nmlib.notmuch_database_create
107 _create.argtypes = [c_char_p]
108 _create.restype = NotmuchDatabaseP
110 def __init__(self, path=None, create=False, mode=0):
111 """If *path* is `None`, we will try to read a users notmuch
112 configuration and use his configured database. The location of the
113 configuration file can be specified through the environment variable
114 *NOTMUCH_CONFIG*, falling back to the default `~/.notmuch-config`.
116 If *create* is `True`, the database will always be created in
117 :attr:`MODE`.READ_WRITE mode. Default mode for opening is READ_ONLY.
119 :param path: Directory to open/create the database in (see
120 above for behavior if `None`)
121 :type path: `str` or `None`
122 :param create: Pass `False` to open an existing, `True` to create a new
125 :param mode: Mode to open a database in. Is always
126 :attr:`MODE`.READ_WRITE when creating a new one.
127 :type mode: :attr:`MODE`
128 :exception: :exc:`NotmuchError` or derived exception in case of
133 # no path specified. use a user's default database
134 if Database._std_db_path is None:
135 #the following line throws a NotmuchError if it fails
136 Database._std_db_path = self._get_user_default_db()
137 path = Database._std_db_path
140 self.open(path, mode)
144 def _assert_db_is_initialized(self):
145 """Raises :exc:`NotInitializedError` if self._db is `None`"""
147 raise NotInitializedError()
149 def create(self, path):
150 """Creates a new notmuch database
152 This function is used by __init__() and usually does not need
153 to be called directly. It wraps the underlying
154 *notmuch_database_create* function and creates a new notmuch
155 database at *path*. It will always return a database in :attr:`MODE`
156 .READ_WRITE mode as creating an empty database for
157 reading only does not make a great deal of sense.
159 :param path: A directory in which we should create the database.
162 :exception: :exc:`NotmuchError` in case of any failure
163 (possibly after printing an error message on stderr).
165 if self._db is not None:
166 raise NotmuchError(message="Cannot create db, this Database() "
167 "already has an open one.")
169 res = Database._create(_str(path), Database.MODE.READ_WRITE)
173 message="Could not create the specified database")
176 def open(self, path, mode=0):
177 """Opens an existing database
179 This function is used by __init__() and usually does not need
180 to be called directly. It wraps the underlying
181 *notmuch_database_open* function.
183 :param status: Open the database in read-only or read-write mode
184 :type status: :attr:`MODE`
186 :exception: Raises :exc:`NotmuchError` in case of any failure
187 (possibly after printing an error message on stderr).
189 res = Database._open(_str(path), mode)
192 raise NotmuchError(message="Could not open the specified database")
196 """Returns the file path of an open database"""
197 self._assert_db_is_initialized()
198 return Database._get_path(self._db).decode('utf-8')
200 def get_version(self):
201 """Returns the database format version
203 :returns: The database version as positive integer
205 self._assert_db_is_initialized()
206 return Database._get_version(self._db)
208 _needs_upgrade = nmlib.notmuch_database_needs_upgrade
209 _needs_upgrade.argtypes = [NotmuchDatabaseP]
210 _needs_upgrade.restype = bool
212 def needs_upgrade(self):
213 """Does this database need to be upgraded before writing to it?
215 If this function returns `True` then no functions that modify the
216 database (:meth:`add_message`,
217 :meth:`Message.add_tag`, :meth:`Directory.set_mtime`,
218 etc.) will work unless :meth:`upgrade` is called successfully first.
220 :returns: `True` or `False`
222 self._assert_db_is_initialized()
223 return self._needs_upgrade(self._db)
226 """Upgrades the current database
228 After opening a database in read-write mode, the client should
229 check if an upgrade is needed (notmuch_database_needs_upgrade) and
230 if so, upgrade with this function before making any modifications.
232 NOT IMPLEMENTED: The optional progress_notify callback can be
233 used by the caller to provide progress indication to the
234 user. If non-NULL it will be called periodically with
235 'progress' as a floating-point value in the range of [0.0..1.0]
236 indicating the progress made so far in the upgrade process.
238 :TODO: catch exceptions, document return values and etc...
240 self._assert_db_is_initialized()
241 status = Database._upgrade(self._db, None, None)
242 #TODO: catch exceptions, document return values and etc
245 _begin_atomic = nmlib.notmuch_database_begin_atomic
246 _begin_atomic.argtypes = [NotmuchDatabaseP]
247 _begin_atomic.restype = c_uint
249 def begin_atomic(self):
250 """Begin an atomic database operation
252 Any modifications performed between a successful
253 :meth:`begin_atomic` and a :meth:`end_atomic` will be applied to
254 the database atomically. Note that, unlike a typical database
255 transaction, this only ensures atomicity, not durability;
256 neither begin nor end necessarily flush modifications to disk.
258 :returns: :attr:`STATUS`.SUCCESS or raises
259 :exception: :exc:`NotmuchError`: :attr:`STATUS`.XAPIAN_EXCEPTION
260 Xapian exception occurred; atomic section not entered.
262 *Added in notmuch 0.9*"""
263 self._assert_db_is_initialized()
264 status = self._begin_atomic(self._db)
265 if status != STATUS.SUCCESS:
266 raise NotmuchError(status)
269 _end_atomic = nmlib.notmuch_database_end_atomic
270 _end_atomic.argtypes = [NotmuchDatabaseP]
271 _end_atomic.restype = c_uint
273 def end_atomic(self):
274 """Indicate the end of an atomic database operation
276 See :meth:`begin_atomic` for details.
278 :returns: :attr:`STATUS`.SUCCESS or raises
282 :attr:`STATUS`.XAPIAN_EXCEPTION
283 A Xapian exception occurred; atomic section not
285 :attr:`STATUS`.UNBALANCED_ATOMIC:
286 end_atomic has been called more times than begin_atomic.
288 *Added in notmuch 0.9*"""
289 self._assert_db_is_initialized()
290 status = self._end_atomic(self._db)
291 if status != STATUS.SUCCESS:
292 raise NotmuchError(status)
295 def get_directory(self, path):
296 """Returns a :class:`Directory` of path,
297 (creating it if it does not exist(?))
301 This call needs a writeable database in
302 :attr:`Database.MODE`.READ_WRITE mode. The underlying library will
303 exit the program if this method is used on a read-only database!
305 :param path: An unicode string containing the path relative to the path
306 of database (see :meth:`get_path`), or else should be an absolute
307 path with initial components that match the path of 'database'.
308 :returns: :class:`Directory` or raises an exception.
310 :exc:`NotmuchError` with :attr:`STATUS`.FILE_ERROR
311 If path is not relative database or absolute with initial
312 components same as database.
314 self._assert_db_is_initialized()
315 # sanity checking if path is valid, and make path absolute
316 if path[0] == os.sep:
317 # we got an absolute path
318 if not path.startswith(self.get_path()):
319 # but its initial components are not equal to the db path
320 raise NotmuchError(STATUS.FILE_ERROR,
321 message="Database().get_directory() called "
322 "with a wrong absolute path.")
325 #we got a relative path, make it absolute
326 abs_dirpath = os.path.abspath(os.path.join(self.get_path(), path))
328 dir_p = Database._get_directory(self._db, _str(path))
330 # return the Directory, init it with the absolute path
331 return Directory(_str(abs_dirpath), dir_p, self)
333 _add_message = nmlib.notmuch_database_add_message
334 _add_message.argtypes = [NotmuchDatabaseP, c_char_p,
335 POINTER(NotmuchMessageP)]
336 _add_message.restype = c_uint
338 def add_message(self, filename, sync_maildir_flags=False):
339 """Adds a new message to the database
341 :param filename: should be a path relative to the path of the
342 open database (see :meth:`get_path`), or else should be an
343 absolute filename with initial components that match the
344 path of the database.
346 The file should be a single mail message (not a
347 multi-message mbox) that is expected to remain at its
348 current location, since the notmuch database will reference
349 the filename, and will not copy the entire contents of the
352 :param sync_maildir_flags: If the message contains Maildir
353 flags, we will -depending on the notmuch configuration- sync
354 those tags to initial notmuch tags, if set to `True`. It is
355 `False` by default to remain consistent with the libnotmuch
356 API. You might want to look into the underlying method
357 :meth:`Message.maildir_flags_to_tags`.
359 :returns: On success, we return
361 1) a :class:`Message` object that can be used for things
362 such as adding tags to the just-added message.
363 2) one of the following :attr:`STATUS` values:
365 :attr:`STATUS`.SUCCESS
366 Message successfully added to database.
367 :attr:`STATUS`.DUPLICATE_MESSAGE_ID
368 Message has the same message ID as another message already
369 in the database. The new filename was successfully added
370 to the list of the filenames for the existing message.
372 :rtype: 2-tuple(:class:`Message`, :attr:`STATUS`)
374 :exception: Raises a :exc:`NotmuchError` with the following meaning.
375 If such an exception occurs, nothing was added to the database.
377 :attr:`STATUS`.FILE_ERROR
378 An error occurred trying to open the file, (such as
379 permission denied, or file not found, etc.).
380 :attr:`STATUS`.FILE_NOT_EMAIL
381 The contents of filename don't look like an email
383 :attr:`STATUS`.READ_ONLY_DATABASE
384 Database was opened in read-only mode so no message can
387 self._assert_db_is_initialized()
388 msg_p = NotmuchMessageP()
389 status = self._add_message(self._db, _str(filename), byref(msg_p))
391 if not status in [STATUS.SUCCESS, STATUS.DUPLICATE_MESSAGE_ID]:
392 raise NotmuchError(status)
394 #construct Message() and return
395 msg = Message(msg_p, self)
396 #automatic sync initial tags from Maildir flags
397 if sync_maildir_flags:
398 msg.maildir_flags_to_tags()
401 _remove_message = nmlib.notmuch_database_remove_message
402 _remove_message.argtypes = [NotmuchDatabaseP, c_char_p]
403 _remove_message.restype = c_uint
405 def remove_message(self, filename):
406 """Removes a message (filename) from the given notmuch database
408 Note that only this particular filename association is removed from
409 the database. If the same message (as determined by the message ID)
410 is still available via other filenames, then the message will
411 persist in the database for those filenames. When the last filename
412 is removed for a particular message, the database content for that
413 message will be entirely removed.
415 :returns: A :attr:`STATUS` value with the following meaning:
417 :attr:`STATUS`.SUCCESS
418 The last filename was removed and the message was removed
420 :attr:`STATUS`.DUPLICATE_MESSAGE_ID
421 This filename was removed but the message persists in the
422 database with at least one other filename.
424 :exception: Raises a :exc:`NotmuchError` with the following meaning.
425 If such an exception occurs, nothing was removed from the
428 :attr:`STATUS`.READ_ONLY_DATABASE
429 Database was opened in read-only mode so no message can be
432 self._assert_db_is_initialized()
433 return self._remove_message(self._db, _str(filename))
435 def find_message(self, msgid):
436 """Returns a :class:`Message` as identified by its message ID
438 Wraps the underlying *notmuch_database_find_message* function.
440 :param msgid: The message ID
441 :type msgid: unicode or str
442 :returns: :class:`Message` or `None` if no message is found.
444 :exc:`OutOfMemoryError`
445 If an Out-of-memory occured while constructing the message.
447 In case of a Xapian Exception. These exceptions
448 include "Database modified" situations, e.g. when the
449 notmuch database has been modified by another program
450 in the meantime. In this case, you should close and
451 reopen the database and retry.
452 :exc:`NotInitializedError` if
453 the database was not intitialized.
455 self._assert_db_is_initialized()
456 msg_p = NotmuchMessageP()
457 status = Database._find_message(self._db, _str(msgid), byref(msg_p))
458 if status != STATUS.SUCCESS:
459 raise NotmuchError(status)
460 return msg_p and Message(msg_p, self) or None
462 def find_message_by_filename(self, filename):
463 """Find a message with the given filename
467 This call needs a writeable database in
468 :attr:`Database.MODE`.READ_WRITE mode. The underlying library will
469 exit the program if this method is used on a read-only database!
471 :returns: If the database contains a message with the given
472 filename, then a class:`Message:` is returned. This
473 function returns None if no message is found with the given
477 :exc:`OutOfMemoryError`
478 If an Out-of-memory occured while constructing the message.
480 In case of a Xapian Exception. These exceptions
481 include "Database modified" situations, e.g. when the
482 notmuch database has been modified by another program
483 in the meantime. In this case, you should close and
484 reopen the database and retry.
485 :exc:`NotInitializedError` if
486 the database was not intitialized.
488 *Added in notmuch 0.9*"""
489 self._assert_db_is_initialized()
490 msg_p = NotmuchMessageP()
491 status = Database._find_message_by_filename(self._db, _str(filename),
493 if status != STATUS.SUCCESS:
494 raise NotmuchError(status)
495 return msg_p and Message(msg_p, self) or None
497 def get_all_tags(self):
498 """Returns :class:`Tags` with a list of all tags found in the database
500 :returns: :class:`Tags`
501 :execption: :exc:`NotmuchError` with :attr:`STATUS`.NULL_POINTER
504 self._assert_db_is_initialized()
505 tags_p = Database._get_all_tags(self._db)
507 raise NotmuchError(STATUS.NULL_POINTER)
508 return Tags(tags_p, self)
510 def create_query(self, querystring):
511 """Returns a :class:`Query` derived from this database
513 This is a shorthand method for doing::
516 # Automatically frees the Database() when 'q' is deleted
518 q = Database(dbpath).create_query('from:"Biene Maja"')
520 # long version, which is functionally equivalent but will keep the
521 # Database in the 'db' variable around after we delete 'q':
523 db = Database(dbpath)
524 q = Query(db,'from:"Biene Maja"')
526 This function is a python extension and not in the underlying C API.
528 return Query(self, querystring)
531 return "'Notmuch DB " + self.get_path() + "'"
533 _close = nmlib.notmuch_database_close
534 _close.argtypes = [NotmuchDatabaseP]
535 _close.restype = None
538 """Close and free the notmuch database if needed"""
539 if self._db is not None:
540 self._close(self._db)
542 def _get_user_default_db(self):
543 """ Reads a user's notmuch config and returns his db location
545 Throws a NotmuchError if it cannot find it"""
548 from configparser import SafeConfigParser
551 from ConfigParser import SafeConfigParser
553 config = SafeConfigParser()
554 conf_f = os.getenv('NOTMUCH_CONFIG',
555 os.path.expanduser('~/.notmuch-config'))
557 if not config.has_option('database', 'path'):
558 raise NotmuchError(message="No DB path specified"
559 " and no user default found")
560 return config.get('database', 'path').decode('utf-8')
564 """Property returning a pointer to `notmuch_database_t` or `None`
566 This should normally not be needed by a user (and is not yet
567 guaranteed to remain stable in future versions).
573 """Represents a search query on an opened :class:`Database`.
575 A query selects and filters a subset of messages from the notmuch
576 database we derive from.
578 :class:`Query` provides an instance attribute :attr:`sort`, which
579 contains the sort order (if specified via :meth:`set_sort`) or
582 Any function in this class may throw an :exc:`NotInitializedError`
583 in case the underlying query object was not set up correctly.
585 .. note:: Do remember that as soon as we tear down this object,
586 all underlying derived objects such as threads,
587 messages, tags etc will be freed by the underlying library
588 as well. Accessing these objects will lead to segfaults and
589 other unexpected behavior. See above for more details.
592 SORT = Enum(['OLDEST_FIRST', 'NEWEST_FIRST', 'MESSAGE_ID', 'UNSORTED'])
593 """Constants: Sort order in which to return results"""
595 """notmuch_query_create"""
596 _create = nmlib.notmuch_query_create
597 _create.argtypes = [NotmuchDatabaseP, c_char_p]
598 _create.restype = NotmuchQueryP
600 """notmuch_query_search_threads"""
601 _search_threads = nmlib.notmuch_query_search_threads
602 _search_threads.argtypes = [NotmuchQueryP]
603 _search_threads.restype = NotmuchThreadsP
605 """notmuch_query_search_messages"""
606 _search_messages = nmlib.notmuch_query_search_messages
607 _search_messages.argtypes = [NotmuchQueryP]
608 _search_messages.restype = NotmuchMessagesP
610 """notmuch_query_count_messages"""
611 _count_messages = nmlib.notmuch_query_count_messages
612 _count_messages.argtypes = [NotmuchQueryP]
613 _count_messages.restype = c_uint
615 def __init__(self, db, querystr):
617 :param db: An open database which we derive the Query from.
618 :type db: :class:`Database`
619 :param querystr: The query string for the message.
620 :type querystr: utf-8 encoded str or unicode
625 self.create(db, querystr)
627 def _assert_query_is_initialized(self):
628 """Raises :exc:`NotInitializedError` if self._query is `None`"""
629 if self._query is None:
630 raise NotInitializedError()
632 def create(self, db, querystr):
633 """Creates a new query derived from a Database
635 This function is utilized by __init__() and usually does not need to
638 :param db: Database to create the query from.
639 :type db: :class:`Database`
640 :param querystr: The query string
641 :type querystr: utf-8 encoded str or unicode
644 :exc:`NullPointerError` if the query creation failed
645 (e.g. too little memory).
646 :exc:`NotInitializedError` if the underlying db was not
649 db._assert_db_is_initialized()
650 # create reference to parent db to keep it alive
652 # create query, return None if too little mem available
653 query_p = Query._create(db.db_p, _str(querystr))
655 raise NullPointerError
656 self._query = query_p
658 _set_sort = nmlib.notmuch_query_set_sort
659 _set_sort.argtypes = [NotmuchQueryP, c_uint]
660 _set_sort.argtypes = None
662 def set_sort(self, sort):
663 """Set the sort order future results will be delivered in
665 :param sort: Sort order (see :attr:`Query.SORT`)
667 self._assert_query_is_initialized()
669 self._set_sort(self._query, sort)
671 def search_threads(self):
672 """Execute a query for threads
674 Execute a query for threads, returning a :class:`Threads` iterator.
675 The returned threads are owned by the query and as such, will only be
676 valid until the Query is deleted.
678 The method sets :attr:`Message.FLAG`\.MATCH for those messages that
679 match the query. The method :meth:`Message.get_flag` allows us
680 to get the value of this flag.
682 :returns: :class:`Threads`
683 :exception: :exc:`NullPointerError` if search_threads failed
685 self._assert_query_is_initialized()
686 threads_p = Query._search_threads(self._query)
688 if threads_p is None:
689 raise NullPointerError
690 return Threads(threads_p, self)
692 def search_messages(self):
693 """Filter messages according to the query and return
694 :class:`Messages` in the defined sort order
696 :returns: :class:`Messages`
697 :exception: :exc:`NullPointerError` if search_messages failed
699 self._assert_query_is_initialized()
700 msgs_p = Query._search_messages(self._query)
703 raise NullPointerError
704 return Messages(msgs_p, self)
706 def count_messages(self):
707 """Estimate the number of messages matching the query
709 This function performs a search and returns Xapian's best
710 guess as to the number of matching messages. It is much faster
711 than performing :meth:`search_messages` and counting the
712 result with `len()` (although it always returned the same
713 result in my tests). Technically, it wraps the underlying
714 *notmuch_query_count_messages* function.
716 :returns: :class:`Messages`
718 self._assert_query_is_initialized()
719 return Query._count_messages(self._query)
721 _destroy = nmlib.notmuch_query_destroy
722 _destroy.argtypes = [NotmuchQueryP]
723 _destroy.restype = None
726 """Close and free the Query"""
727 if self._query is not None:
728 self._destroy(self._query)
731 class Directory(object):
732 """Represents a directory entry in the notmuch directory
734 Modifying attributes of this object will modify the
735 database, not the real directory attributes.
737 The Directory object is usually derived from another object
738 e.g. via :meth:`Database.get_directory`, and will automatically be
739 become invalid whenever that parent is deleted. You should
740 therefore initialized this object handing it a reference to the
741 parent, preventing the parent from automatically being garbage
745 """notmuch_directory_get_mtime"""
746 _get_mtime = nmlib.notmuch_directory_get_mtime
747 _get_mtime.argtypes = [NotmuchDirectoryP]
748 _get_mtime.restype = c_long
750 """notmuch_directory_set_mtime"""
751 _set_mtime = nmlib.notmuch_directory_set_mtime
752 _set_mtime.argtypes = [NotmuchDirectoryP, c_long]
753 _set_mtime.restype = c_uint
755 """notmuch_directory_get_child_files"""
756 _get_child_files = nmlib.notmuch_directory_get_child_files
757 _get_child_files.argtypes = [NotmuchDirectoryP]
758 _get_child_files.restype = NotmuchFilenamesP
760 """notmuch_directory_get_child_directories"""
761 _get_child_directories = nmlib.notmuch_directory_get_child_directories
762 _get_child_directories.argtypes = [NotmuchDirectoryP]
763 _get_child_directories.restype = NotmuchFilenamesP
765 def _assert_dir_is_initialized(self):
766 """Raises a NotmuchError(:attr:`STATUS`.NOT_INITIALIZED)
768 if self._dir_p is None:
769 raise NotmuchError(STATUS.NOT_INITIALIZED)
771 def __init__(self, path, dir_p, parent):
773 :param path: The absolute path of the directory object as unicode.
774 :param dir_p: The pointer to an internal notmuch_directory_t object.
775 :param parent: The object this Directory is derived from
776 (usually a :class:`Database`). We do not directly use
777 this, but store a reference to it as long as
778 this Directory object lives. This keeps the
781 assert isinstance(path, unicode), "Path needs to be an UNICODE object"
784 self._parent = parent
786 def set_mtime(self, mtime):
787 """Sets the mtime value of this directory in the database
789 The intention is for the caller to use the mtime to allow efficient
790 identification of new messages to be added to the database. The
791 recommended usage is as follows:
793 * Read the mtime of a directory from the filesystem
795 * Call :meth:`Database.add_message` for all mail files in
798 * Call notmuch_directory_set_mtime with the mtime read from the
799 filesystem. Then, when wanting to check for updates to the
800 directory in the future, the client can call :meth:`get_mtime`
801 and know that it only needs to add files if the mtime of the
802 directory and files are newer than the stored timestamp.
806 :meth:`get_mtime` function does not allow the caller to
807 distinguish a timestamp of 0 from a non-existent timestamp. So
808 don't store a timestamp of 0 unless you are comfortable with
811 :param mtime: A (time_t) timestamp
812 :returns: Nothing on success, raising an exception on failure.
813 :exception: :exc:`NotmuchError`:
815 :attr:`STATUS`.XAPIAN_EXCEPTION
816 A Xapian exception occurred, mtime not stored.
817 :attr:`STATUS`.READ_ONLY_DATABASE
818 Database was opened in read-only mode so directory
819 mtime cannot be modified.
820 :attr:`STATUS`.NOT_INITIALIZED
821 The directory has not been initialized
823 self._assert_dir_is_initialized()
824 #TODO: make sure, we convert the mtime parameter to a 'c_long'
825 status = Directory._set_mtime(self._dir_p, mtime)
828 if status == STATUS.SUCCESS:
830 #fail with Exception otherwise
831 raise NotmuchError(status)
834 """Gets the mtime value of this directory in the database
836 Retrieves a previously stored mtime for this directory.
838 :param mtime: A (time_t) timestamp
839 :returns: Nothing on success, raising an exception on failure.
840 :exception: :exc:`NotmuchError`:
842 :attr:`STATUS`.NOT_INITIALIZED
843 The directory has not been initialized
845 self._assert_dir_is_initialized()
846 return Directory._get_mtime(self._dir_p)
848 # Make mtime attribute a property of Directory()
849 mtime = property(get_mtime, set_mtime, doc="""Property that allows getting
850 and setting of the Directory *mtime* (read-write)
852 See :meth:`get_mtime` and :meth:`set_mtime` for usage and
853 possible exceptions.""")
855 def get_child_files(self):
856 """Gets a Filenames iterator listing all the filenames of
857 messages in the database within the given directory.
859 The returned filenames will be the basename-entries only (not
862 self._assert_dir_is_initialized()
863 files_p = Directory._get_child_files(self._dir_p)
864 return Filenames(files_p, self)
866 def get_child_directories(self):
867 """Gets a :class:`Filenames` iterator listing all the filenames of
868 sub-directories in the database within the given directory
870 The returned filenames will be the basename-entries only (not
873 self._assert_dir_is_initialized()
874 files_p = Directory._get_child_directories(self._dir_p)
875 return Filenames(files_p, self)
879 """Returns the absolute path of this Directory (read-only)"""
883 """Object representation"""
884 return "<notmuch Directory object '%s'>" % self._path
886 _destroy = nmlib.notmuch_directory_destroy
887 _destroy.argtypes = [NotmuchDirectoryP]
888 _destroy.argtypes = None
891 """Close and free the Directory"""
892 if self._dir_p is not None:
893 self._destroy(self._dir_p)
896 class Filenames(object):
897 """An iterator over File- or Directory names stored in the database"""
899 #notmuch_filenames_get
900 _get = nmlib.notmuch_filenames_get
901 _get.argtypes = [NotmuchFilenamesP]
902 _get.restype = c_char_p
904 def __init__(self, files_p, parent):
906 :param files_p: The pointer to an internal notmuch_filenames_t object.
907 :param parent: The object this Directory is derived from
908 (usually a Directory()). We do not directly use
909 this, but store a reference to it as long as
910 this Directory object lives. This keeps the
913 self._files_p = files_p
914 self._parent = parent
917 """ Make Filenames an iterator """
920 _valid = nmlib.notmuch_filenames_valid
921 _valid.argtypes = [NotmuchFilenamesP]
922 _valid.restype = bool
924 _move_to_next = nmlib.notmuch_filenames_move_to_next
925 _move_to_next.argtypes = [NotmuchFilenamesP]
926 _move_to_next.restype = None
929 if self._files_p is None:
930 raise NotmuchError(STATUS.NOT_INITIALIZED)
932 if not self._valid(self._files_p):
936 file_ = Filenames._get(self._files_p)
937 self._move_to_next(self._files_p)
938 return file_.decode('utf-8', 'ignore')
939 next = __next__ # python2.x iterator protocol compatibility
942 """len(:class:`Filenames`) returns the number of contained files
946 As this iterates over the files, we will not be able to
947 iterate over them again! So this will fail::
950 files = Database().get_directory('').get_child_files()
951 if len(files) > 0: # this 'exhausts' msgs
953 # NotmuchError(:attr:`STATUS`.NOT_INITIALIZED)
954 for file in files: print file
956 if self._files_p is None:
957 raise NotmuchError(STATUS.NOT_INITIALIZED)
960 while self._valid(self._files_p):
961 self._move_to_next(self._files_p)
966 _destroy = nmlib.notmuch_filenames_destroy
967 _destroy.argtypes = [NotmuchFilenamesP]
968 _destroy.restype = None
971 """Close and free Filenames"""
972 if self._files_p is not None:
973 self._destroy(self._files_p)