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