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_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
28 class Database(object):
29 """Represents a notmuch database (wraps notmuch_database_t)
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.
38 """Class attribute to cache user's default database"""
40 MODE = Enum(['READ_ONLY', 'READ_WRITE'])
41 """Constants: Mode in which to open the database"""
43 """notmuch_database_get_directory"""
44 _get_directory = nmlib.notmuch_database_get_directory
45 _get_directory.restype = c_void_p
47 """notmuch_database_get_path"""
48 _get_path = nmlib.notmuch_database_get_path
49 _get_path.restype = c_char_p
51 """notmuch_database_get_version"""
52 _get_version = nmlib.notmuch_database_get_version
53 _get_version.restype = c_uint
55 """notmuch_database_open"""
56 _open = nmlib.notmuch_database_open
57 _open.restype = c_void_p
59 """notmuch_database_upgrade"""
60 _upgrade = nmlib.notmuch_database_upgrade
61 _upgrade.argtypes = [c_void_p, c_void_p, c_void_p]
63 """ notmuch_database_find_message"""
64 _find_message = nmlib.notmuch_database_find_message
66 """notmuch_database_find_message_by_filename"""
67 _find_message_by_filename = nmlib.notmuch_database_find_message_by_filename
69 """notmuch_database_get_all_tags"""
70 _get_all_tags = nmlib.notmuch_database_get_all_tags
71 _get_all_tags.restype = c_void_p
73 """notmuch_database_create"""
74 _create = nmlib.notmuch_database_create
75 _create.restype = c_void_p
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`.
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.
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
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
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
107 self.open(path, mode)
111 def _assert_db_is_initialized(self):
112 """Raises :exc:`NotInitializedError` if self._db is `None`"""
114 raise NotInitializedError()
116 def create(self, path):
117 """Creates a new notmuch database
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.
126 :param path: A directory in which we should create the database.
129 :exception: :exc:`NotmuchError` in case of any failure
130 (possibly after printing an error message on stderr).
132 if self._db is not None:
133 raise NotmuchError(message="Cannot create db, this Database() "
134 "already has an open one.")
136 res = Database._create(_str(path), Database.MODE.READ_WRITE)
140 message="Could not create the specified database")
143 def open(self, path, mode=0):
144 """Opens an existing database
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.
150 :param status: Open the database in read-only or read-write mode
151 :type status: :attr:`MODE`
153 :exception: Raises :exc:`NotmuchError` in case
154 of any failure (after printing an error message on stderr).
156 res = Database._open(_str(path), mode)
159 raise NotmuchError(message="Could not open the specified database")
163 """Returns the file path of an open database
165 .. ..:: Wraps underlying `notmuch_database_get_path`"""
166 self._assert_db_is_initialized()
167 return Database._get_path(self._db).decode('utf-8')
169 def get_version(self):
170 """Returns the database format version
172 :returns: The database version as positive integer
173 :exception: :exc:`NotInitializedError` if
174 the database was not intitialized.
176 self._assert_db_is_initialized()
177 return Database._get_version(self._db)
179 def needs_upgrade(self):
180 """Does this database need to be upgraded before writing to it?
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.
187 :returns: `True` or `False`
188 :exception: :exc:`NotInitializedError` if
189 the database was not intitialized.
191 self._assert_db_is_initialized()
192 return nmlib.notmuch_database_needs_upgrade(self._db)
195 """Upgrades the current database
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.
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.
207 :TODO: catch exceptions, document return values and etc...
209 :exception: :exc:`NotInitializedError` if
210 the database was not intitialized.
212 self._assert_db_is_initialized()
213 status = Database._upgrade(self._db, None, None)
214 #TODO: catch exceptions, document return values and etc
217 def begin_atomic(self):
218 """Begin an atomic database operation
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.
226 :returns: :attr:`STATUS`.SUCCESS or raises
228 :exception: :exc:`NotmuchError`:
229 :attr:`STATUS`.XAPIAN_EXCEPTION
230 Xapian exception occurred; atomic section not entered.
232 :exc:`NotInitializedError` if
233 the database was not intitialized.
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)
242 def end_atomic(self):
243 """Indicate the end of an atomic database operation
245 See :meth:`begin_atomic` for details.
247 :returns: :attr:`STATUS`.SUCCESS or raises
251 :attr:`STATUS`.XAPIAN_EXCEPTION
252 A Xapian exception occurred; atomic section not
254 :attr:`STATUS`.UNBALANCED_ATOMIC:
255 end_atomic has been called more times than begin_atomic.
257 :exc:`NotInitializedError` if
258 the database was not intitialized.
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)
267 def get_directory(self, path):
268 """Returns a :class:`Directory` of path,
269 (creating it if it does not exist(?))
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!
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.
280 :exc:`NotmuchError` with :attr:`STATUS`.FILE_ERROR
281 If path is not relative database or absolute with initial
282 components same as database.
284 :exc:`NotInitializedError` if
285 the database was not intitialized.
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.")
298 #we got a relative path, make it absolute
299 abs_dirpath = os.path.abspath(os.path.join(self.get_path(), path))
301 dir_p = Database._get_directory(self._db, _str(path))
303 # return the Directory, init it with the absolute path
304 return Directory(_str(abs_dirpath), dir_p, self)
306 def add_message(self, filename, sync_maildir_flags=False):
307 """Adds a new message to the database
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.
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
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`.
327 :returns: On success, we return
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:
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.
340 :rtype: 2-tuple(:class:`Message`, :attr:`STATUS`)
342 :exception: Raises a :exc:`NotmuchError` with the following meaning.
343 If such an exception occurs, nothing was added to the database.
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
351 :attr:`STATUS`.READ_ONLY_DATABASE
352 Database was opened in read-only mode so no message can
355 :exc:`NotInitializedError` if
356 the database was not intitialized.
358 self._assert_db_is_initialized()
360 status = nmlib.notmuch_database_add_message(self._db,
364 if not status in [STATUS.SUCCESS, STATUS.DUPLICATE_MESSAGE_ID]:
365 raise NotmuchError(status)
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()
374 def remove_message(self, filename):
375 """Removes a message (filename) from the given notmuch database
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.
384 :returns: A :attr:`STATUS` value with the following meaning:
386 :attr:`STATUS`.SUCCESS
387 The last filename was removed and the message was removed
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.
393 :exception: Raises a :exc:`NotmuchError` with the following meaning.
394 If such an exception occurs, nothing was removed from the
397 :attr:`STATUS`.READ_ONLY_DATABASE
398 Database was opened in read-only mode so no message can be
401 :exc:`NotInitializedError` if
402 the database was not intitialized.
404 self._assert_db_is_initialized()
405 return nmlib.notmuch_database_remove_message(self._db,
408 def find_message(self, msgid):
409 """Returns a :class:`Message` as identified by its message ID
411 Wraps the underlying *notmuch_database_find_message* function.
413 :param msgid: The message ID
414 :type msgid: unicode or str
415 :returns: :class:`Message` or `None` if no message is found.
417 :exc:`OutOfMemoryError`
418 If an Out-of-memory occured while constructing the message.
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.
428 self._assert_db_is_initialized()
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
435 def find_message_by_filename(self, filename):
436 """Find a message with the given filename
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
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
449 :exc:`OutOfMemoryError`
450 If an Out-of-memory occured while constructing the message.
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.
460 *Added in notmuch 0.9*"""
461 self._assert_db_is_initialized()
463 status = Database._find_message_by_filename(self._db, _str(filename),
465 if status != STATUS.SUCCESS:
466 raise NotmuchError(status)
467 return msg_p and Message(msg_p, self) or None
469 def get_all_tags(self):
470 """Returns :class:`Tags` with a list of all tags found in the database
472 :returns: :class:`Tags`
473 :execption: :exc:`NotmuchError` with :attr:`STATUS`.NULL_POINTER on error
475 self._assert_db_is_initialized()
476 tags_p = Database._get_all_tags(self._db)
478 raise NotmuchError(STATUS.NULL_POINTER)
479 return Tags(tags_p, self)
481 def create_query(self, querystring):
482 """Returns a :class:`Query` derived from this database
484 This is a shorthand method for doing::
487 # Automatically frees the Database() when 'q' is deleted
489 q = Database(dbpath).create_query('from:"Biene Maja"')
491 # long version, which is functionally equivalent but will keep the
492 # Database in the 'db' variable around after we delete 'q':
494 db = Database(dbpath)
495 q = Query(db,'from:"Biene Maja"')
497 This function is a python extension and not in the underlying C API.
499 self._assert_db_is_initialized()
500 return Query(self, querystring)
503 return "'Notmuch DB " + self.get_path() + "'"
506 """Close and free the notmuch database if needed"""
507 if self._db is not None:
508 nmlib.notmuch_database_close(self._db)
510 def _get_user_default_db(self):
511 """ Reads a user's notmuch config and returns his db location
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'))
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')
526 """Property returning a pointer to `notmuch_database_t` or `None`
528 This should normally not be needed by a user (and is not yet
529 guaranteed to remain stable in future versions).
535 """Represents a search query on an opened :class:`Database`.
537 A query selects and filters a subset of messages from the notmuch
538 database we derive from.
540 Query() provides an instance attribute :attr:`sort`, which
541 contains the sort order (if specified via :meth:`set_sort`) or
544 Technically, it wraps the underlying *notmuch_query_t* struct.
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.
553 SORT = Enum(['OLDEST_FIRST', 'NEWEST_FIRST', 'MESSAGE_ID', 'UNSORTED'])
554 """Constants: Sort order in which to return results"""
556 """notmuch_query_create"""
557 _create = nmlib.notmuch_query_create
558 _create.restype = c_void_p
560 """notmuch_query_search_threads"""
561 _search_threads = nmlib.notmuch_query_search_threads
562 _search_threads.restype = c_void_p
564 """notmuch_query_search_messages"""
565 _search_messages = nmlib.notmuch_query_search_messages
566 _search_messages.restype = c_void_p
568 """notmuch_query_count_messages"""
569 _count_messages = nmlib.notmuch_query_count_messages
570 _count_messages.restype = c_uint
572 def __init__(self, db, querystr):
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
582 self.create(db, querystr)
584 def create(self, db, querystr):
585 """Creates a new query derived from a Database
587 This function is utilized by __init__() and usually does not need to
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
595 :exception: :exc:`NotmuchError`
597 * :attr:`STATUS`.NOT_INITIALIZED if db is not inited
598 * :attr:`STATUS`.NULL_POINTER if the query creation failed
602 raise NotmuchError(STATUS.NOT_INITIALIZED)
603 # create reference to parent db to keep it alive
605 # create query, return None if too little mem available
606 query_p = Query._create(db.db_p, _str(querystr))
608 raise NotmuchError(STATUS.NULL_POINTER)
609 self._query = query_p
611 def set_sort(self, sort):
612 """Set the sort order future results will be delivered in
614 Wraps the underlying *notmuch_query_set_sort* function.
616 :param sort: Sort order (see :attr:`Query.SORT`)
618 :exception: :exc:`NotmuchError` :attr:`STATUS`.NOT_INITIALIZED if query has not
621 if self._query is None:
622 raise NotmuchError(STATUS.NOT_INITIALIZED)
625 nmlib.notmuch_query_set_sort(self._query, sort)
627 def search_threads(self):
628 """Execute a query for threads
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.
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.
638 Technically, it wraps the underlying
639 *notmuch_query_search_threads* function.
641 :returns: :class:`Threads`
642 :exception: :exc:`NotmuchError`
644 * :attr:`STATUS`.NOT_INITIALIZED if query is not inited
645 * :attr:`STATUS`.NULL_POINTER if search_threads failed
647 if self._query is None:
648 raise NotmuchError(STATUS.NOT_INITIALIZED)
650 threads_p = Query._search_threads(self._query)
652 if threads_p is None:
653 raise NotmuchError(STATUS.NULL_POINTER)
655 return Threads(threads_p, self)
657 def search_messages(self):
658 """Filter messages according to the query and return
659 :class:`Messages` in the defined sort order
661 Technically, it wraps the underlying
662 *notmuch_query_search_messages* function.
664 :returns: :class:`Messages`
665 :exception: :exc:`NotmuchError`
667 * :attr:`STATUS`.NOT_INITIALIZED if query is not inited
668 * :attr:`STATUS`.NULL_POINTER if search_messages failed
670 if self._query is None:
671 raise NotmuchError(STATUS.NOT_INITIALIZED)
673 msgs_p = Query._search_messages(self._query)
676 raise NotmuchError(STATUS.NULL_POINTER)
678 return Messages(msgs_p, self)
680 def count_messages(self):
681 """Estimate the number of messages matching the query
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.
690 :returns: :class:`Messages`
691 :exception: :exc:`NotmuchError`
693 * :attr:`STATUS`.NOT_INITIALIZED if query is not inited
695 if self._query is None:
696 raise NotmuchError(STATUS.NOT_INITIALIZED)
698 return Query._count_messages(self._query)
701 """Close and free the Query"""
702 if self._query is not None:
703 nmlib.notmuch_query_destroy(self._query)
706 class Directory(object):
707 """Represents a directory entry in the notmuch directory
709 Modifying attributes of this object will modify the
710 database, not the real directory attributes.
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
720 """notmuch_directory_get_mtime"""
721 _get_mtime = nmlib.notmuch_directory_get_mtime
722 _get_mtime.restype = c_long
724 """notmuch_directory_set_mtime"""
725 _set_mtime = nmlib.notmuch_directory_set_mtime
726 _set_mtime.argtypes = [c_char_p, c_long]
728 """notmuch_directory_get_child_files"""
729 _get_child_files = nmlib.notmuch_directory_get_child_files
730 _get_child_files.restype = c_void_p
732 """notmuch_directory_get_child_directories"""
733 _get_child_directories = nmlib.notmuch_directory_get_child_directories
734 _get_child_directories.restype = c_void_p
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)
741 def __init__(self, path, dir_p, parent):
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
751 assert isinstance(path, unicode), "Path needs to be an UNICODE object"
754 self._parent = parent
756 def set_mtime(self, mtime):
757 """Sets the mtime value of this directory in the database
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:
763 * Read the mtime of a directory from the filesystem
765 * Call :meth:`Database.add_message` for all mail files in
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.
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.
779 :param mtime: A (time_t) timestamp
780 :returns: Nothing on success, raising an exception on failure.
781 :exception: :exc:`NotmuchError`:
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
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)
796 if status == STATUS.SUCCESS:
798 #fail with Exception otherwise
799 raise NotmuchError(status)
802 """Gets the mtime value of this directory in the database
804 Retrieves a previously stored mtime for this directory.
806 :param mtime: A (time_t) timestamp
807 :returns: Nothing on success, raising an exception on failure.
808 :exception: :exc:`NotmuchError`:
810 :attr:`STATUS`.NOT_INITIALIZED
811 The directory has not been initialized
813 self._assert_dir_is_initialized()
814 return Directory._get_mtime(self._dir_p)
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)
820 See :meth:`get_mtime` and :meth:`set_mtime` for usage and
821 possible exceptions.""")
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.
827 The returned filenames will be the basename-entries only (not
830 self._assert_dir_is_initialized()
831 files_p = Directory._get_child_files(self._dir_p)
832 return Filenames(files_p, self)
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
838 The returned filenames will be the basename-entries only (not
841 self._assert_dir_is_initialized()
842 files_p = Directory._get_child_directories(self._dir_p)
843 return Filenames(files_p, self)
847 """Returns the absolute path of this Directory (read-only)"""
851 """Object representation"""
852 return "<notmuch Directory object '%s'>" % self._path
855 """Close and free the Directory"""
856 if self._dir_p is not None:
857 nmlib.notmuch_directory_destroy(self._dir_p)
860 class Filenames(object):
861 """An iterator over File- or Directory names stored in the database"""
863 #notmuch_filenames_get
864 _get = nmlib.notmuch_filenames_get
865 _get.restype = c_char_p
867 def __init__(self, files_p, parent):
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
876 self._files_p = files_p
877 self._parent = parent
880 """ Make Filenames an iterator """
884 if self._files_p is None:
885 raise NotmuchError(STATUS.NOT_INITIALIZED)
887 if not nmlib.notmuch_filenames_valid(self._files_p):
891 file = Filenames._get(self._files_p)
892 nmlib.notmuch_filenames_move_to_next(self._files_p)
896 """len(:class:`Filenames`) returns the number of contained files
898 .. note:: As this iterates over the files, we will not be able to
899 iterate over them again! So this will fail::
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
907 if self._files_p is None:
908 raise NotmuchError(STATUS.NOT_INITIALIZED)
911 while nmlib.notmuch_filenames_valid(self._files_p):
912 nmlib.notmuch_filenames_move_to_next(self._files_p)
918 """Close and free Filenames"""
919 if self._files_p is not None:
920 nmlib.notmuch_filenames_destroy(self._files_p)