diff options
| author | David Bremner <bremner@debian.org> | 2011-12-16 16:46:20 -0400 |
|---|---|---|
| committer | David Bremner <bremner@debian.org> | 2011-12-16 16:46:20 -0400 |
| commit | 90259bf961eeacb89dfd2e73526a931e530cabd8 (patch) | |
| tree | c8c5d57ebba3f82e372e8d2670257ac01d68fca4 /bindings/python | |
| parent | 8c0cb84ecce40ded56f9c551b2ef791caa9be7cf (diff) | |
| parent | 07bb8b9e895541006eca88430925f1c6524c4708 (diff) | |
Merge commit 'debian/0.10.2-1' into squeeze-backports
Conflicts:
debian/changelog
Diffstat (limited to 'bindings/python')
| -rw-r--r-- | bindings/python/.gitignore | 3 | ||||
| -rw-r--r-- | bindings/python/docs/source/index.rst | 29 | ||||
| -rw-r--r-- | bindings/python/docs/source/status_and_errors.rst | 28 | ||||
| -rw-r--r-- | bindings/python/notmuch/__init__.py | 33 | ||||
| -rw-r--r-- | bindings/python/notmuch/database.py | 524 | ||||
| -rw-r--r-- | bindings/python/notmuch/filename.py | 35 | ||||
| -rw-r--r-- | bindings/python/notmuch/globals.py | 114 | ||||
| -rw-r--r-- | bindings/python/notmuch/message.py | 160 | ||||
| -rw-r--r-- | bindings/python/notmuch/tag.py | 47 | ||||
| -rw-r--r-- | bindings/python/notmuch/thread.py | 81 | ||||
| -rw-r--r-- | bindings/python/notmuch/version.py | 2 | ||||
| -rw-r--r-- | bindings/python/setup.py | 26 |
12 files changed, 616 insertions, 466 deletions
diff --git a/bindings/python/.gitignore b/bindings/python/.gitignore new file mode 100644 index 00000000..1fbea8a0 --- /dev/null +++ b/bindings/python/.gitignore @@ -0,0 +1,3 @@ +*.py[co] +/docs/build +/docs/html diff --git a/bindings/python/docs/source/index.rst b/bindings/python/docs/source/index.rst index e9f39eb0..73d2a3b0 100644 --- a/bindings/python/docs/source/index.rst +++ b/bindings/python/docs/source/index.rst @@ -21,7 +21,13 @@ Notmuch can be imported as:: or:: - from notmuch import Query,Database + from notmuch import Query, Database + + db = Database('path',create=True) + msgs = Query(db,'from:myself').search_messages() + + for msg in msgs: + print (msg) More information on specific topics can be found on the following pages: @@ -36,8 +42,6 @@ More information on specific topics can be found on the following pages: .. automodule:: notmuch -:todo: Document nmlib,STATUS - :class:`notmuch.Database` -- The underlying notmuch database --------------------------------------------------------------------- @@ -55,6 +59,10 @@ More information on specific topics can be found on the following pages: .. automethod:: upgrade + .. automethod:: begin_atomic + + .. automethod:: end_atomic + .. automethod:: get_directory .. automethod:: add_message @@ -63,13 +71,12 @@ More information on specific topics can be found on the following pages: .. automethod:: find_message + .. automethod:: find_message_by_filename + .. automethod:: get_all_tags .. automethod:: create_query - .. note:: :meth:`create_query` was broken in release - 0.1 and is fixed since 0.1.1. - .. attribute:: Database.MODE Defines constants that are used as the mode in which to open a database. @@ -82,6 +89,7 @@ More information on specific topics can be found on the following pages: .. autoattribute:: db_p + :class:`notmuch.Query` -- A search query ------------------------------------------------- @@ -130,7 +138,7 @@ More information on specific topics can be found on the following pages: .. method:: __len__() - .. note:: :meth:`__len__` was removed in version 0.6 as it exhausted + .. warning:: :meth:`__len__` was removed in version 0.6 as it exhausted the iterator and broke list(Messages()). Use the :meth:`Query.count_messages` function or use `len(list(msgs))`. @@ -195,7 +203,12 @@ More information on specific topics can be found on the following pages: .. autoclass:: Tags :members: - .. automethod:: __len__ + .. method:: __len__ + + .. warning:: :meth:`__len__` was removed in version 0.6 as it + exhausted the iterator and broke list(Tags()). Use + :meth:`len(list(msgs))` instead if you need to know the + number of tags. .. automethod:: __str__ diff --git a/bindings/python/docs/source/status_and_errors.rst b/bindings/python/docs/source/status_and_errors.rst index 1d74ba17..bc0d0d23 100644 --- a/bindings/python/docs/source/status_and_errors.rst +++ b/bindings/python/docs/source/status_and_errors.rst @@ -15,9 +15,31 @@ Some methods return a status, indicating if an operation was successful and what :exc:`NotmuchError` -- A Notmuch execution error ------------------------------------------------ -Whenever an error occurs, we throw a special Exception: +Whenever an error occurs, we throw a special Exception :exc:`NotmuchError`, or a more fine grained Exception which is derived from it. This means it is always safe to check for NotmuchErrors if you want to catch all errors. If you are interested in more fine grained exceptions, you can use those below. .. autoexception:: NotmuchError - :members: - This execption inherits directly from :exc:`Exception` and is raised on errors during the notmuch execution. +The following exceptions are all directly derived from NotmuchError. Each of them corresponds to a specific :class:`notmuch.STATUS` value. You can either check the :attr:`status` attribute of a NotmuchError to see if a specific error has occurred, or you can directly check for the following Exception types: + +.. autoexception:: OutOfMemoryError(message=None) + :members: +.. autoexception:: ReadOnlyDatabaseError(message=None) + :members: +.. autoexception:: XapianError(message=None) + :members: +.. autoexception:: FileError(message=None) + :members: +.. autoexception:: FileNotEmailError(message=None) + :members: +.. autoexception:: DuplicateMessageIdError(message=None) + :members: +.. autoexception:: NullPointerError(message=None) + :members: +.. autoexception:: TagTooLongError(message=None) + :members: +.. autoexception:: UnbalancedFreezeThawError(message=None) + :members: +.. autoexception:: UnbalancedAtomicError(message=None) + :members: +.. autoexception:: NotInitializedError(message=None) + :members: diff --git a/bindings/python/notmuch/__init__.py b/bindings/python/notmuch/__init__.py index 4331d9de..539afedf 100644 --- a/bindings/python/notmuch/__init__.py +++ b/bindings/python/notmuch/__init__.py @@ -1,9 +1,10 @@ -"""The :mod:`notmuch` module provides most of the functionality that a user is likely to need. +"""The :mod:`notmuch` module provides most of the functionality that a user is +likely to need. .. note:: The underlying notmuch library is build on a hierarchical memory allocator called talloc. All objects derive from a top-level :class:`Database` object. - + This means that as soon as an object is deleted, all underlying derived objects such as Queries, Messages, Message, and Tags will be freed by the underlying library as well. Accessing these @@ -16,7 +17,7 @@ db = Database('path',create=True) msgs = Query(db,'from:myself').search_messages() - This returns a :class:`Messages` which internally contains a + This returns :class:`Messages` which internally contains a reference to its parent :class:`Query` object. Otherwise the Query() would be immediately freed, taking our *msgs* down with it. @@ -30,7 +31,6 @@ Pretty much the same is valid for all other objects in the hierarchy, such as :class:`Query`, :class:`Messages`, :class:`Message`, and :class:`Tags`. - """ """ @@ -49,13 +49,28 @@ for more details. You should have received a copy of the GNU General Public License along with notmuch. If not, see <http://www.gnu.org/licenses/>. -Copyright 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>' +Copyright 2010-2011 Sebastian Spaeth <Sebastian@SSpaeth.de> """ from notmuch.database import Database, Query from notmuch.message import Messages, Message from notmuch.thread import Threads, Thread from notmuch.tag import Tags -from notmuch.globals import nmlib, STATUS, NotmuchError -__LICENSE__="GPL v3+" -__VERSION__='0.6' -__AUTHOR__ ='Sebastian Spaeth <Sebastian@SSpaeth.de>' +from notmuch.globals import ( + nmlib, + STATUS, + NotmuchError, + OutOfMemoryError, + ReadOnlyDatabaseError, + XapianError, + FileError, + FileNotEmailError, + DuplicateMessageIdError, + NullPointerError, + TagTooLongError, + UnbalancedFreezeThawError, + UnbalancedAtomicError, + NotInitializedError +) +from notmuch.version import __VERSION__ +__LICENSE__ = "GPL v3+" +__AUTHOR__ = 'Sebastian Spaeth <Sebastian@SSpaeth.de>' diff --git a/bindings/python/notmuch/database.py b/bindings/python/notmuch/database.py index 5deb2a5d..f4bc53e0 100644 --- a/bindings/python/notmuch/database.py +++ b/bindings/python/notmuch/database.py @@ -19,24 +19,39 @@ Copyright 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>' import os from ctypes import c_int, c_char_p, c_void_p, c_uint, c_long, byref -from notmuch.globals import nmlib, STATUS, NotmuchError, Enum +from notmuch.globals import (nmlib, STATUS, NotmuchError, NotInitializedError, + NullPointerError, OutOfMemoryError, XapianError, Enum, _str) from notmuch.thread import Threads from notmuch.message import Messages, Message from notmuch.tag import Tags class Database(object): - """Represents a notmuch database (wraps notmuch_database_t) + """The :class:`Database` is the highest-level object that notmuch + provides. It references a notmuch database, and can be opened in + read-only or read-write mode. A :class:`Query` can be derived from + or be applied to a specific database to find messages. Also adding + and removing messages to the database happens via this + object. Modifications to the database are not atmic by default (see + :meth:`begin_atomic`) and once a database has been modified, all + other database objects pointing to the same data-base will throw an + :exc:`XapianError` as the underlying database has been + modified. Close and reopen the database to continue working with it. - .. note:: Do remember that as soon as we tear down this object, - all underlying derived objects such as queries, threads, - messages, tags etc will be freed by the underlying library - as well. Accessing these objects will lead to segfaults and - other unexpected behavior. See above for more details. + .. note:: Any function in this class can and will throw an + :exc:`NotInitializedError` if the database was not + intitialized properly. + + .. note:: Do remember that as soon as we tear down (e.g. via `del + db`) this object, all underlying derived objects such as + queries, threads, messages, tags etc will be freed by the + underlying library as well. Accessing these objects will lead + to segfaults and other unexpected behavior. See above for + more details. """ _std_db_path = None """Class attribute to cache user's default database""" - MODE = Enum(['READ_ONLY','READ_WRITE']) + MODE = Enum(['READ_ONLY', 'READ_WRITE']) """Constants: Mode in which to open the database""" """notmuch_database_get_directory""" @@ -52,7 +67,7 @@ class Database(object): _get_version.restype = c_uint """notmuch_database_open""" - _open = nmlib.notmuch_database_open + _open = nmlib.notmuch_database_open _open.restype = c_void_p """notmuch_database_upgrade""" @@ -61,7 +76,9 @@ class Database(object): """ notmuch_database_find_message""" _find_message = nmlib.notmuch_database_find_message - _find_message.restype = c_void_p + + """notmuch_database_find_message_by_filename""" + _find_message_by_filename = nmlib.notmuch_database_find_message_by_filename """notmuch_database_get_all_tags""" _get_all_tags = nmlib.notmuch_database_get_all_tags @@ -71,9 +88,9 @@ class Database(object): _create = nmlib.notmuch_database_create _create.restype = c_void_p - def __init__(self, path=None, create=False, mode= 0): - """If *path* is `None`, we will try to read a users notmuch - configuration and use his configured database. The location of the + def __init__(self, path=None, create=False, mode=0): + """If *path* is `None`, we will try to read a users notmuch + configuration and use his configured database. The location of the configuration file can be specified through the environment variable *NOTMUCH_CONFIG*, falling back to the default `~/.notmuch-config`. @@ -84,13 +101,13 @@ class Database(object): above for behavior if `None`) :type path: `str` or `None` :param create: Pass `False` to open an existing, `True` to create a new - database. + database. :type create: bool - :param mode: Mode to open a database in. Is always + :param mode: Mode to open a database in. Is always :attr:`MODE`.READ_WRITE when creating a new one. :type mode: :attr:`MODE` - :returns: Nothing - :exception: :exc:`NotmuchError` in case of failure. + :exception: :exc:`NotmuchError` or derived exception in case of + failure. """ self._db = None if path is None: @@ -100,16 +117,15 @@ class Database(object): Database._std_db_path = self._get_user_default_db() path = Database._std_db_path - assert isinstance(path, basestring), 'Path needs to be a string or None.' if create == False: self.open(path, mode) else: self.create(path) - def _verify_initialized_db(self): - """Raises a NotmuchError in case self._db is still None""" + def _assert_db_is_initialized(self): + """Raises :exc:`NotInitializedError` if self._db is `None`""" if self._db is None: - raise NotmuchError(STATUS.NOT_INITIALIZED) + raise NotInitializedError() def create(self, path): """Creates a new notmuch database @@ -125,20 +141,20 @@ class Database(object): :type path: str :returns: Nothing :exception: :exc:`NotmuchError` in case of any failure - (after printing an error message on stderr). + (possibly after printing an error message on stderr). """ if self._db is not None: - raise NotmuchError( - message="Cannot create db, this Database() already has an open one.") + raise NotmuchError(message="Cannot create db, this Database() " + "already has an open one.") - res = Database._create(path, Database.MODE.READ_WRITE) + res = Database._create(_str(path), Database.MODE.READ_WRITE) if res is None: raise NotmuchError( message="Could not create the specified database") self._db = res - def open(self, path, mode= 0): + def open(self, path, mode=0): """Opens an existing database This function is used by __init__() and usually does not need @@ -146,39 +162,29 @@ class Database(object): *notmuch_database_open* function. :param status: Open the database in read-only or read-write mode - :type status: :attr:`MODE` + :type status: :attr:`MODE` :returns: Nothing :exception: Raises :exc:`NotmuchError` in case - of any failure (after printing an error message on stderr). + of any failure (possibly after printing an error message on stderr). """ - - res = Database._open(path, mode) + res = Database._open(_str(path), mode) if res is None: - raise NotmuchError( - message="Could not open the specified database") + raise NotmuchError(message="Could not open the specified database") self._db = res def get_path(self): - """Returns the file path of an open database - - Wraps *notmuch_database_get_path*.""" - # Raise a NotmuchError if not initialized - self._verify_initialized_db() - - return Database._get_path(self._db) + """Returns the file path of an open database""" + self._assert_db_is_initialized() + return Database._get_path(self._db).decode('utf-8') def get_version(self): """Returns the database format version :returns: The database version as positive integer - :exception: :exc:`NotmuchError` with STATUS.NOT_INITIALIZED if - the database was not intitialized. """ - # Raise a NotmuchError if not initialized - self._verify_initialized_db() - - return Database._get_version (self._db) + self._assert_db_is_initialized() + return Database._get_version(self._db) def needs_upgrade(self): """Does this database need to be upgraded before writing to it? @@ -189,13 +195,9 @@ class Database(object): etc.) will work unless :meth:`upgrade` is called successfully first. :returns: `True` or `False` - :exception: :exc:`NotmuchError` with STATUS.NOT_INITIALIZED if - the database was not intitialized. """ - # Raise a NotmuchError if not initialized - self._verify_initialized_db() - - return notmuch_database_needs_upgrade(self._db) + self._assert_db_is_initialized() + return nmlib.notmuch_database_needs_upgrade(self._db) def upgrade(self): """Upgrades the current database @@ -207,72 +209,109 @@ class Database(object): NOT IMPLEMENTED: The optional progress_notify callback can be used by the caller to provide progress indication to the user. If non-NULL it will be called periodically with - 'progress' as a floating-point value in the range of [0.0..1.0] + 'progress' as a floating-point value in the range of [0.0..1.0] indicating the progress made so far in the upgrade process. :TODO: catch exceptions, document return values and etc... """ - # Raise a NotmuchError if not initialized - self._verify_initialized_db() - - status = Database._upgrade (self._db, None, None) + self._assert_db_is_initialized() + status = Database._upgrade(self._db, None, None) #TODO: catch exceptions, document return values and etc return status + def begin_atomic(self): + """Begin an atomic database operation + + Any modifications performed between a successful + :meth:`begin_atomic` and a :meth:`end_atomic` will be applied to + the database atomically. Note that, unlike a typical database + transaction, this only ensures atomicity, not durability; + neither begin nor end necessarily flush modifications to disk. + + :returns: :attr:`STATUS`.SUCCESS or raises + + :exception: :exc:`NotmuchError`: + :attr:`STATUS`.XAPIAN_EXCEPTION + Xapian exception occurred; atomic section not entered. + + *Added in notmuch 0.9*""" + self._assert_db_is_initialized() + status = nmlib.notmuch_database_begin_atomic(self._db) + if status != STATUS.SUCCESS: + raise NotmuchError(status) + return status + + def end_atomic(self): + """Indicate the end of an atomic database operation + + See :meth:`begin_atomic` for details. + + :returns: :attr:`STATUS`.SUCCESS or raises + + :exception: + :exc:`NotmuchError`: + :attr:`STATUS`.XAPIAN_EXCEPTION + A Xapian exception occurred; atomic section not + ended. + :attr:`STATUS`.UNBALANCED_ATOMIC: + end_atomic has been called more times than begin_atomic. + + *Added in notmuch 0.9*""" + self._assert_db_is_initialized() + status = nmlib.notmuch_database_end_atomic(self._db) + if status != STATUS.SUCCESS: + raise NotmuchError(status) + return status + def get_directory(self, path): - """Returns a :class:`Directory` of path, + """Returns a :class:`Directory` of path, (creating it if it does not exist(?)) - .. warning:: This call needs a writeable database in - Database.MODE.READ_WRITE mode. The underlying library will exit the + .. warning:: This call needs a writeable database in + :attr:`Database.MODE`.READ_WRITE mode. The underlying library will exit the program if this method is used on a read-only database! - :param path: A str containing the path relative to the path of database - (see :meth:`get_path`), or else should be an absolute path + :param path: An unicode string containing the path relative to the path + of database (see :meth:`get_path`), or else should be an absolute path with initial components that match the path of 'database'. :returns: :class:`Directory` or raises an exception. - :exception: :exc:`NotmuchError` - - STATUS.NOT_INITIALIZED - If the database was not intitialized. - - STATUS.FILE_ERROR - If path is not relative database or absolute with initial + :exception: + :exc:`NotmuchError` with :attr:`STATUS`.FILE_ERROR + If path is not relative database or absolute with initial components same as database. - """ - # Raise a NotmuchError if not initialized - self._verify_initialized_db() - + self._assert_db_is_initialized() # sanity checking if path is valid, and make path absolute if path[0] == os.sep: # we got an absolute path if not path.startswith(self.get_path()): # but its initial components are not equal to the db path - raise NotmuchError(STATUS.FILE_ERROR, - message="Database().get_directory() called with a wrong absolute path.") + raise NotmuchError(STATUS.FILE_ERROR, + message="Database().get_directory() called " + "with a wrong absolute path.") abs_dirpath = path else: #we got a relative path, make it absolute - abs_dirpath = os.path.abspath(os.path.join(self.get_path(),path)) + abs_dirpath = os.path.abspath(os.path.join(self.get_path(), path)) - dir_p = Database._get_directory(self._db, path); + dir_p = Database._get_directory(self._db, _str(path)) # return the Directory, init it with the absolute path - return Directory(abs_dirpath, dir_p, self) + return Directory(_str(abs_dirpath), dir_p, self) def add_message(self, filename, sync_maildir_flags=False): """Adds a new message to the database - :param filename: should be a path relative to the path of the open - database (see :meth:`get_path`), or else should be an absolute - filename with initial components that match the path of the - database. + :param filename: should be a path relative to the path of the + open database (see :meth:`get_path`), or else should be an + absolute filename with initial components that match the + path of the database. - The file should be a single mail message (not a multi-message mbox) - that is expected to remain at its current location, since the - notmuch database will reference the filename, and will not copy the - entire contents of the file. + The file should be a single mail message (not a + multi-message mbox) that is expected to remain at its + current location, since the notmuch database will reference + the filename, and will not copy the entire contents of the + file. :param sync_maildir_flags: If the message contains Maildir flags, we will -depending on the notmuch configuration- sync @@ -281,43 +320,40 @@ class Database(object): API. You might want to look into the underlying method :meth:`Message.maildir_flags_to_tags`. - :returns: On success, we return + :returns: On success, we return 1) a :class:`Message` object that can be used for things such as adding tags to the just-added message. - 2) one of the following STATUS values: + 2) one of the following :attr:`STATUS` values: - STATUS.SUCCESS + :attr:`STATUS`.SUCCESS Message successfully added to database. - STATUS.DUPLICATE_MESSAGE_ID + :attr:`STATUS`.DUPLICATE_MESSAGE_ID Message has the same message ID as another message already in the database. The new filename was successfully added - to the message in the database. + to the list of the filenames for the existing message. - :rtype: 2-tuple(:class:`Message`, STATUS) + :rtype: 2-tuple(:class:`Message`, :attr:`STATUS`) :exception: Raises a :exc:`NotmuchError` with the following meaning. If such an exception occurs, nothing was added to the database. - STATUS.FILE_ERROR - An error occurred trying to open the file, (such as + :attr:`STATUS`.FILE_ERROR + An error occurred trying to open the file, (such as permission denied, or file not found, etc.). - STATUS.FILE_NOT_EMAIL - The contents of filename don't look like an email message. - STATUS.READ_ONLY_DATABASE + :attr:`STATUS`.FILE_NOT_EMAIL + The contents of filename don't look like an email + message. + :attr:`STATUS`.READ_ONLY_DATABASE Database was opened in read-only mode so no message can be added. - STATUS.NOT_INITIALIZED - The database has not been initialized. """ - # Raise a NotmuchError if not initialized - self._verify_initialized_db() - + self._assert_db_is_initialized() msg_p = c_void_p() status = nmlib.notmuch_database_add_message(self._db, - filename, + _str(filename), byref(msg_p)) - + if not status in [STATUS.SUCCESS, STATUS.DUPLICATE_MESSAGE_ID]: raise NotmuchError(status) @@ -329,7 +365,7 @@ class Database(object): return (msg, status) def remove_message(self, filename): - """Removes a message from the given notmuch database + """Removes a message (filename) from the given notmuch database Note that only this particular filename association is removed from the database. If the same message (as determined by the message ID) @@ -338,27 +374,24 @@ class Database(object): is removed for a particular message, the database content for that message will be entirely removed. - :returns: A STATUS value with the following meaning: + :returns: A :attr:`STATUS` value with the following meaning: - STATUS.SUCCESS - The last filename was removed and the message was removed + :attr:`STATUS`.SUCCESS + The last filename was removed and the message was removed from the database. - STATUS.DUPLICATE_MESSAGE_ID - This filename was removed but the message persists in the + :attr:`STATUS`.DUPLICATE_MESSAGE_ID + This filename was removed but the message persists in the database with at least one other filename. :exception: Raises a :exc:`NotmuchError` with the following meaning. - If such an exception occurs, nothing was removed from the database. + If such an exception occurs, nothing was removed from the + database. - STATUS.READ_ONLY_DATABASE - Database was opened in read-only mode so no message can be + :attr:`STATUS`.READ_ONLY_DATABASE + Database was opened in read-only mode so no message can be removed. - STATUS.NOT_INITIALIZED - The database has not been initialized. """ - # Raise a NotmuchError if not initialized - self._verify_initialized_db() - + self._assert_db_is_initialized() return nmlib.notmuch_database_remove_message(self._db, filename) @@ -368,36 +401,69 @@ class Database(object): Wraps the underlying *notmuch_database_find_message* function. :param msgid: The message ID - :type msgid: string - :returns: :class:`Message` or `None` if no message is found or - if any xapian exception or out-of-memory situation - occurs. Do note that Xapian Exceptions include - "Database modified" situations, e.g. when the - notmuch database has been modified by - another program in the meantime. A return value of - `None` is therefore no guarantee that the message - does not exist. - :exception: :exc:`NotmuchError` with STATUS.NOT_INITIALIZED if - the database was not intitialized. + :type msgid: unicode or str + :returns: :class:`Message` or `None` if no message is found. + :exception: + :exc:`OutOfMemoryError` + If an Out-of-memory occured while constructing the message. + :exc:`XapianError` + In case of a Xapian Exception. These exceptions + include "Database modified" situations, e.g. when the + notmuch database has been modified by another program + in the meantime. In this case, you should close and + reopen the database and retry. + :exc:`NotInitializedError` if + the database was not intitialized. """ - # Raise a NotmuchError if not initialized - self._verify_initialized_db() + self._assert_db_is_initialized() + msg_p = c_void_p() + status = Database._find_message(self._db, _str(msgid), byref(msg_p)) + if status != STATUS.SUCCESS: + raise NotmuchError(status) + return msg_p and Message(msg_p, self) or None + + def find_message_by_filename(self, filename): + """Find a message with the given filename - msg_p = Database._find_message(self._db, msgid) - if msg_p is None: - return None - return Message(msg_p, self) + .. warning:: This call needs a writeable database in + :attr:`Database.MODE`.READ_WRITE mode. The underlying library will + exit the program if this method is used on a read-only + database! + + :returns: If the database contains a message with the given + filename, then a class:`Message:` is returned. This + function returns None if no message is found with the given + filename. + + :exception: + :exc:`OutOfMemoryError` + If an Out-of-memory occured while constructing the message. + :exc:`XapianError` + In case of a Xapian Exception. These exceptions + include "Database modified" situations, e.g. when the + notmuch database has been modified by another program + in the meantime. In this case, you should close and + reopen the database and retry. + :exc:`NotInitializedError` if + the database was not intitialized. + + *Added in notmuch 0.9*""" + self._assert_db_is_initialized() + msg_p = c_void_p() + status = Database._find_message_by_filename(self._db, _str(filename), + byref(msg_p)) + if status != STATUS.SUCCESS: + raise NotmuchError(status) + return msg_p and Message(msg_p, self) or None def get_all_tags(self): """Returns :class:`Tags` with a list of all tags found in the database :returns: :class:`Tags` - :execption: :exc:`NotmuchError` with STATUS.NULL_POINTER on error + :execption: :exc:`NotmuchError` with :attr:`STATUS`.NULL_POINTER on error """ - # Raise a NotmuchError if not initialized - self._verify_initialized_db() - - tags_p = Database._get_all_tags (self._db) + self._assert_db_is_initialized() + tags_p = Database._get_all_tags(self._db) if tags_p == None: raise NotmuchError(STATUS.NULL_POINTER) return Tags(tags_p, self) @@ -420,9 +486,6 @@ class Database(object): This function is a python extension and not in the underlying C API. """ - # Raise a NotmuchError if not initialized - self._verify_initialized_db() - return Query(self, querystring) def __repr__(self): @@ -442,10 +505,10 @@ class Database(object): conf_f = os.getenv('NOTMUCH_CONFIG', os.path.expanduser('~/.notmuch-config')) config.read(conf_f) - if not config.has_option('database','path'): - raise NotmuchError(message= - "No DB path specified and no user default found") - return config.get('database','path') + if not config.has_option('database', 'path'): + raise NotmuchError(message="No DB path specified" + " and no user default found") + return config.get('database', 'path').decode('utf-8') @property def db_p(self): @@ -456,18 +519,19 @@ class Database(object): """ return self._db -#------------------------------------------------------------------------------ + class Query(object): """Represents a search query on an opened :class:`Database`. A query selects and filters a subset of messages from the notmuch database we derive from. - Query() provides an instance attribute :attr:`sort`, which + :class:`Query` provides an instance attribute :attr:`sort`, which contains the sort order (if specified via :meth:`set_sort`) or `None`. - Technically, it wraps the underlying *notmuch_query_t* struct. + Any function in this class may throw an :exc:`NotInitializedError` + in case the underlying query object was not set up correctly. .. note:: Do remember that as soon as we tear down this object, all underlying derived objects such as threads, @@ -476,7 +540,7 @@ class Query(object): other unexpected behavior. See above for more details. """ # constants - SORT = Enum(['OLDEST_FIRST','NEWEST_FIRST','MESSAGE_ID', 'UNSORTED']) + SORT = Enum(['OLDEST_FIRST', 'NEWEST_FIRST', 'MESSAGE_ID', 'UNSORTED']) """Constants: Sort order in which to return results""" """notmuch_query_create""" @@ -491,7 +555,6 @@ class Query(object): _search_messages = nmlib.notmuch_query_search_messages _search_messages.restype = c_void_p - """notmuch_query_count_messages""" _count_messages = nmlib.notmuch_query_count_messages _count_messages.restype = c_uint @@ -501,54 +564,50 @@ class Query(object): :param db: An open database which we derive the Query from. :type db: :class:`Database` :param querystr: The query string for the message. - :type querystr: str + :type querystr: utf-8 encoded str or unicode """ self._db = None self._query = None self.sort = None self.create(db, querystr) + def _assert_query_is_initialized(self): + """Raises :exc:`NotInitializedError` if self._query is `None`""" + if self._query is None: + raise NotInitializedError() + def create(self, db, querystr): """Creates a new query derived from a Database - This function is utilized by __init__() and usually does not need to + This function is utilized by __init__() and usually does not need to be called directly. :param db: Database to create the query from. :type db: :class:`Database` :param querystr: The query string - :type querystr: str + :type querystr: utf-8 encoded str or unicode :returns: Nothing - :exception: :exc:`NotmuchError` - - * STATUS.NOT_INITIALIZED if db is not inited - * STATUS.NULL_POINTER if the query creation failed - (too little memory) + :exception: + :exc:`NullPointerError` if the query creation failed + (e.g. too little memory). + :exc:`NotInitializedError` if the underlying db was not + intitialized. """ - if db.db_p is None: - raise NotmuchError(STATUS.NOT_INITIALIZED) + db._assert_db_is_initialized() # create reference to parent db to keep it alive self._db = db - # create query, return None if too little mem available - query_p = Query._create(db.db_p, querystr) + query_p = Query._create(db.db_p, _str(querystr)) if query_p is None: - NotmuchError(STATUS.NULL_POINTER) + raise NullPointerError self._query = query_p def set_sort(self, sort): """Set the sort order future results will be delivered in - Wraps the underlying *notmuch_query_set_sort* function. - :param sort: Sort order (see :attr:`Query.SORT`) - :returns: Nothing - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if query has not - been initialized. """ - if self._query is None: - raise NotmuchError(STATUS.NOT_INITIALIZED) - + self._assert_query_is_initialized() self.sort = sort nmlib.notmuch_query_set_sort(self._query, sort) @@ -556,54 +615,36 @@ class Query(object): """Execute a query for threads Execute a query for threads, returning a :class:`Threads` iterator. - The returned threads are owned by the query and as such, will only be + The returned threads are owned by the query and as such, will only be valid until the Query is deleted. The method sets :attr:`Message.FLAG`\.MATCH for those messages that match the query. The method :meth:`Message.get_flag` allows us to get the value of this flag. - Technically, it wraps the underlying - *notmuch_query_search_threads* function. - :returns: :class:`Threads` - :exception: :exc:`NotmuchError` - - * STATUS.NOT_INITIALIZED if query is not inited - * STATUS.NULL_POINTER if search_threads failed + :exception: :exc:`NullPointerError` if search_threads failed """ - if self._query is None: - raise NotmuchError(STATUS.NOT_INITIALIZED) - + self._assert_query_is_initialized() threads_p = Query._search_threads(self._query) if threads_p is None: - NotmuchError(STATUS.NULL_POINTER) - - return Threads(threads_p,self) + raise NullPointerError + return Threads(threads_p, self) def search_messages(self): """Filter messages according to the query and return :class:`Messages` in the defined sort order - Technically, it wraps the underlying - *notmuch_query_search_messages* function. - :returns: :class:`Messages` - :exception: :exc:`NotmuchError` - - * STATUS.NOT_INITIALIZED if query is not inited - * STATUS.NULL_POINTER if search_messages failed + :exception: :exc:`NullPointerError` if search_messages failed """ - if self._query is None: - raise NotmuchError(STATUS.NOT_INITIALIZED) - + self._assert_query_is_initialized() msgs_p = Query._search_messages(self._query) if msgs_p is None: - NotmuchError(STATUS.NULL_POINTER) - - return Messages(msgs_p,self) + raise NullPointerError + return Messages(msgs_p, self) def count_messages(self): """Estimate the number of messages matching the query @@ -616,22 +657,16 @@ class Query(object): *notmuch_query_count_messages* function. :returns: :class:`Messages` - :exception: :exc:`NotmuchError` - - * STATUS.NOT_INITIALIZED if query is not inited """ - if self._query is None: - raise NotmuchError(STATUS.NOT_INITIALIZED) - + self._assert_query_is_initialized() return Query._count_messages(self._query) def __del__(self): """Close and free the Query""" if self._query is not None: - nmlib.notmuch_query_destroy (self._query) + nmlib.notmuch_query_destroy(self._query) -#------------------------------------------------------------------------------ class Directory(object): """Represents a directory entry in the notmuch directory @@ -662,14 +697,14 @@ class Directory(object): _get_child_directories = nmlib.notmuch_directory_get_child_directories _get_child_directories.restype = c_void_p - def _verify_dir_initialized(self): - """Raises a NotmuchError(STATUS.NOT_INITIALIZED) if the dir_p is None""" + def _assert_dir_is_initialized(self): + """Raises a NotmuchError(:attr:`STATUS`.NOT_INITIALIZED) if dir_p is None""" if self._dir_p is None: - raise NotmuchError(STATUS.NOT_INITIALIZED) + raise NotmuchError(STATUS.NOT_INITIALIZED) def __init__(self, path, dir_p, parent): """ - :param path: The absolute path of the directory object. + :param path: The absolute path of the directory object as unicode. :param dir_p: The pointer to an internal notmuch_directory_t object. :param parent: The object this Directory is derived from (usually a :class:`Database`). We do not directly use @@ -677,12 +712,12 @@ class Directory(object): this Directory object lives. This keeps the parent object alive. """ + assert isinstance(path, unicode), "Path needs to be an UNICODE object" self._path = path self._dir_p = dir_p self._parent = parent - - def set_mtime (self, mtime): + def set_mtime(self, mtime): """Sets the mtime value of this directory in the database The intention is for the caller to use the mtime to allow efficient @@ -690,36 +725,34 @@ class Directory(object): recommended usage is as follows: * Read the mtime of a directory from the filesystem - + * Call :meth:`Database.add_message` for all mail files in the directory - * Call notmuch_directory_set_mtime with the mtime read from the + * Call notmuch_directory_set_mtime with the mtime read from the filesystem. Then, when wanting to check for updates to the directory in the future, the client can call :meth:`get_mtime` - and know that it only needs to add files if the mtime of the + and know that it only needs to add files if the mtime of the directory and files are newer than the stored timestamp. - .. note:: :meth:`get_mtime` function does not allow the caller + .. note:: :meth:`get_mtime` function does not allow the caller to distinguish a timestamp of 0 from a non-existent timestamp. So don't store a timestamp of 0 unless you are - comfortable with that. + comfortable with that. - :param mtime: A (time_t) timestamp + :param mtime: A (time_t) timestamp :returns: Nothing on success, raising an exception on failure. :exception: :exc:`NotmuchError`: - STATUS.XAPIAN_EXCEPTION + :attr:`STATUS`.XAPIAN_EXCEPTION A Xapian exception occurred, mtime not stored. - STATUS.READ_ONLY_DATABASE - Database was opened in read-only mode so directory + :attr:`STATUS`.READ_ONLY_DATABASE + Database was opened in read-only mode so directory mtime cannot be modified. - STATUS.NOT_INITIALIZED + :attr:`STATUS`.NOT_INITIALIZED The directory has not been initialized """ - #Raise a NotmuchError(STATUS.NOT_INITIALIZED) if the dir_p is None - self._verify_dir_initialized() - + self._assert_dir_is_initialized() #TODO: make sure, we convert the mtime parameter to a 'c_long' status = Directory._set_mtime(self._dir_p, mtime) @@ -729,53 +762,47 @@ class Directory(object): #fail with Exception otherwise raise NotmuchError(status) - def get_mtime (self): + def get_mtime(self): """Gets the mtime value of this directory in the database Retrieves a previously stored mtime for this directory. - :param mtime: A (time_t) timestamp + :param mtime: A (time_t) timestamp :returns: Nothing on success, raising an exception on failure. :exception: :exc:`NotmuchError`: - STATUS.NOT_INITIALIZED + :attr:`STATUS`.NOT_INITIALIZED The directory has not been initialized """ - #Raise a NotmuchError(STATUS.NOT_INITIALIZED) if self.dir_p is None - self._verify_dir_initialized() - - return Directory._get_mtime (self._dir_p) + self._assert_dir_is_initialized() + return Directory._get_mtime(self._dir_p) # Make mtime attribute a property of Directory() mtime = property(get_mtime, set_mtime, doc="""Property that allows getting and setting of the Directory *mtime* (read-write) - See :meth:`get_mtime` and :meth:`set_mtime` for usage and + See :meth:`get_mtime` and :meth:`set_mtime` for usage and possible exceptions.""") def get_child_files(self): """Gets a Filenames iterator listing all the filenames of messages in the database within the given directory. - + The returned filenames will be the basename-entries only (not complete paths. """ - #Raise a NotmuchError(STATUS.NOT_INITIALIZED) if self._dir_p is None - self._verify_dir_initialized() - + self._assert_dir_is_initialized() files_p = Directory._get_child_files(self._dir_p) return Filenames(files_p, self) def get_child_directories(self): """Gets a :class:`Filenames` iterator listing all the filenames of sub-directories in the database within the given directory - + The returned filenames will be the basename-entries only (not complete paths. """ - #Raise a NotmuchError(STATUS.NOT_INITIALIZED) if self._dir_p is None - self._verify_dir_initialized() - + self._assert_dir_is_initialized() files_p = Directory._get_child_directories(self._dir_p) return Filenames(files_p, self) @@ -793,10 +820,9 @@ class Directory(object): if self._dir_p is not None: nmlib.notmuch_directory_destroy(self._dir_p) -#------------------------------------------------------------------------------ + class Filenames(object): - """An iterator over File- or Directory names that are stored in the database - """ + """An iterator over File- or Directory names stored in the database""" #notmuch_filenames_get _get = nmlib.notmuch_filenames_get @@ -826,26 +852,26 @@ class Filenames(object): self._files_p = None raise StopIteration - file = Filenames._get (self._files_p) + file = Filenames._get(self._files_p) nmlib.notmuch_filenames_move_to_next(self._files_p) return file def __len__(self): """len(:class:`Filenames`) returns the number of contained files - .. note:: As this iterates over the files, we will not be able to + .. note:: As this iterates over the files, we will not be able to iterate over them again! So this will fail:: #THIS FAILS files = Database().get_directory('').get_child_files() if len(files) > 0: #this 'exhausts' msgs - # next line raises NotmuchError(STATUS.NOT_INITIALIZED)!!! + # next line raises NotmuchError(:attr:`STATUS`.NOT_INITIALIZED)!!! for file in files: print file """ if self._files_p is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - i=0 + i = 0 while nmlib.notmuch_filenames_valid(self._files_p): nmlib.notmuch_filenames_move_to_next(self._files_p) i += 1 diff --git a/bindings/python/notmuch/filename.py b/bindings/python/notmuch/filename.py index 20b90e98..de4d785a 100644 --- a/bindings/python/notmuch/filename.py +++ b/bindings/python/notmuch/filename.py @@ -19,19 +19,20 @@ Copyright 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>' from ctypes import c_char_p from notmuch.globals import nmlib, STATUS, NotmuchError -#------------------------------------------------------------------------------ + class Filenames(object): """Represents a list of filenames as returned by notmuch - This object contains the Filenames iterator. The main function is as_generator() which will return a generator so we can do a Filenamesth an iterator over a list of notmuch filenames. Do - note that the underlying library only provides a one-time iterator - (it cannot reset the iterator to the start). Thus iterating over - the function will "exhaust" the list of tags, and a subsequent - iteration attempt will raise a :exc:`NotmuchError` - STATUS.NOT_INITIALIZED. Also note, that any function that uses - iteration (nearly all) will also exhaust the tags. So both:: + This object contains the Filenames iterator. The main function is + as_generator() which will return a generator so we can do a Filenamesth an + iterator over a list of notmuch filenames. Do note that the underlying + library only provides a one-time iterator (it cannot reset the iterator to + the start). Thus iterating over the function will "exhaust" the list of + tags, and a subsequent iteration attempt will raise a :exc:`NotmuchError` + STATUS.NOT_INITIALIZED. Also note, that any function that uses iteration + (nearly all) will also exhaust the tags. So both:: - for name in filenames: print name + for name in filenames: print name as well as:: @@ -67,7 +68,7 @@ class Filenames(object): once all derived objects are dead. """ if files_p is None: - NotmuchError(STATUS.NULL_POINTER) + raise NotmuchError(STATUS.NULL_POINTER) self._files = files_p #save reference to parent object so we keep it alive @@ -81,14 +82,12 @@ class Filenames(object): if self._files is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - if not nmlib.notmuch_filenames_valid(self._files): - self._files = None - return + while nmlib.notmuch_filenames_valid(self._files): + yield Filenames._get(self._files) + nmlib.notmuch_filenames_move_to_next(self._files) + + self._files = None - file = Filenames._get (self._files) - nmlib.notmuch_filenames_move_to_next(self._files) - yield file - def __str__(self): """Represent Filenames() as newline-separated list of full paths @@ -105,4 +104,4 @@ class Filenames(object): def __del__(self): """Close and free the notmuch filenames""" if self._files is not None: - nmlib.notmuch_filenames_destroy (self._files) + nmlib.notmuch_filenames_destroy(self._files) diff --git a/bindings/python/notmuch/globals.py b/bindings/python/notmuch/globals.py index c675d044..de1db161 100644 --- a/bindings/python/notmuch/globals.py +++ b/bindings/python/notmuch/globals.py @@ -23,18 +23,18 @@ from ctypes.util import find_library #----------------------------------------------------------------------------- #package-global instance of the notmuch library try: - nmlib = CDLL("libnotmuch.so.1") + nmlib = CDLL("libnotmuch.so.2") except: raise ImportError("Could not find shared 'notmuch' library.") -#----------------------------------------------------------------------------- + class Enum(object): """Provides ENUMS as "code=Enum(['a','b','c'])" where code.a=0 etc...""" def __init__(self, names): for number, name in enumerate(names): setattr(self, name, number) -#----------------------------------------------------------------------------- + class Status(Enum): """Enum with a string representation of a notmuch_status_t value.""" _status2str = nmlib.notmuch_status_to_string @@ -49,10 +49,10 @@ class Status(Enum): @classmethod def status2str(self, status): - """Get a string representation of a notmuch_status_t value.""" + """Get a string representation of a notmuch_status_t value.""" # define strings for custom error messages if status == STATUS.NOT_INITIALIZED: - return "Operation on uninitialized object impossible." + return "Operation on uninitialized object impossible." return str(Status._status2str(status)) STATUS = Status(['SUCCESS', @@ -65,8 +65,12 @@ STATUS = Status(['SUCCESS', 'NULL_POINTER', 'TAG_TOO_LONG', 'UNBALANCED_FREEZE_THAW', + 'UNBALANCED_ATOMIC', 'NOT_INITIALIZED']) -"""STATUS is a class, whose attributes provide constants that serve as return indicators for notmuch functions. Currently the following ones are defined. For possible return values and specific meaning for each method, see the method description. +"""STATUS is a class, whose attributes provide constants that serve as return +indicators for notmuch functions. Currently the following ones are defined. For +possible return values and specific meaning for each method, see the method +description. * SUCCESS * OUT_OF_MEMORY @@ -78,17 +82,103 @@ STATUS = Status(['SUCCESS', * NULL_POINTER * TAG_TOO_LONG * UNBALANCED_FREEZE_THAW + * UNBALANCED_ATOMIC * NOT_INITIALIZED - Invoke the class method `notmuch.STATUS.status2str` with a status value as argument to receive a human readable string""" -STATUS.__name__ = 'STATUS' +Invoke the class method `notmuch.STATUS.status2str` with a status value as +argument to receive a human readable string""" +STATUS.__name__ = 'STATUS' class NotmuchError(Exception): + """Is initiated with a (notmuch.STATUS[, message=None]). It will not + return an instance of the class NotmuchError, but a derived instance + of a more specific Error Message, e.g. OutOfMemoryError. Each status + but SUCCESS has a corresponding subclassed Exception.""" + + @classmethod + def get_exc_subclass(cls, status): + """Returns a fine grained Exception() type,detailing the error status""" + subclasses = { + STATUS.OUT_OF_MEMORY: OutOfMemoryError, + STATUS.READ_ONLY_DATABASE: ReadOnlyDatabaseError, + STATUS.XAPIAN_EXCEPTION: XapianError, + STATUS.FILE_ERROR: FileError, + STATUS.FILE_NOT_EMAIL: FileNotEmailError, + STATUS.DUPLICATE_MESSAGE_ID: DuplicateMessageIdError, + STATUS.NULL_POINTER: NullPointerError, + STATUS.TAG_TOO_LONG: TagTooLongError, + STATUS.UNBALANCED_FREEZE_THAW: UnbalancedFreezeThawError, + STATUS.UNBALANCED_ATOMIC: UnbalancedAtomicError, + STATUS.NOT_INITIALIZED: NotInitializedError + } + assert 0 < status <= len(subclasses) + return subclasses[status] + + def __new__(cls, *args, **kwargs): + """Return a correct subclass of NotmuchError if needed + + We return a NotmuchError instance if status is None (or 0) and a + subclass that inherits from NotmuchError depending on the + 'status' parameter otherwise.""" + # get 'status'. Passed in as arg or kwarg? + status = args[0] if len(args) else kwargs.get('status', None) + # no 'status' or cls is subclass already, return 'cls' instance + if not status or cls != NotmuchError: + return super(NotmuchError, cls).__new__(cls) + subclass = cls.get_exc_subclass(status) # which class to use? + return subclass.__new__(subclass, *args, **kwargs) + def __init__(self, status=None, message=None): - """Is initiated with a (notmuch.STATUS[,message=None])""" - super(NotmuchError, self).__init__(message, status) + self.status = status + self.message = message def __str__(self): - if self.args[0] is not None: return self.args[0] - else: return STATUS.status2str(self.args[1]) + if self.message is not None: + return self.message + elif self.status is not None: + return STATUS.status2str(self.status) + else: + return 'Unknown error' + +# List of Subclassed exceptions that correspond to STATUS values and are +# subclasses of NotmuchError. +class OutOfMemoryError(NotmuchError): + status = STATUS.OUT_OF_MEMORY +class ReadOnlyDatabaseError(NotmuchError): + status = STATUS.READ_ONLY_DATABASE +class XapianError(NotmuchError): + status = STATUS.XAPIAN_EXCEPTION +class FileError(NotmuchError): + status = STATUS.FILE_ERROR +class FileNotEmailError(NotmuchError): + status = STATUS.FILE_NOT_EMAIL +class DuplicateMessageIdError(NotmuchError): + status = STATUS.DUPLICATE_MESSAGE_ID +class NullPointerError(NotmuchError): + status = STATUS.NULL_POINTER +class TagTooLongError(NotmuchError): + status = STATUS.TAG_TOO_LONG +class UnbalancedFreezeThawError(NotmuchError): + status = STATUS.UNBALANCED_FREEZE_THAW +class UnbalancedAtomicError(NotmuchError): + status = STATUS.UNBALANCED_ATOMIC +class NotInitializedError(NotmuchError): + """Derived from NotmuchError, this occurs if the underlying data + structure (e.g. database is not initialized (yet) or an iterator has + been exhausted. You can test for NotmuchError with .status = + STATUS.NOT_INITIALIZED""" + status = STATUS.NOT_INITIALIZED + + + +def _str(value): + """Ensure a nicely utf-8 encoded string to pass to libnotmuch + + C++ code expects strings to be well formatted and + unicode strings to have no null bytes.""" + if not isinstance(value, basestring): + raise TypeError("Expected str or unicode, got %s" % str(type(value))) + if isinstance(value, unicode): + return value.encode('UTF-8') + return value diff --git a/bindings/python/notmuch/message.py b/bindings/python/notmuch/message.py index 763d2c68..4bf90c22 100644 --- a/bindings/python/notmuch/message.py +++ b/bindings/python/notmuch/message.py @@ -18,10 +18,10 @@ Copyright 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>' Jesse Rosenthal <jrosenthal@jhu.edu> """ - + from ctypes import c_char_p, c_void_p, c_long, c_uint, c_int from datetime import date -from notmuch.globals import nmlib, STATUS, NotmuchError, Enum +from notmuch.globals import nmlib, STATUS, NotmuchError, Enum, _str from notmuch.tag import Tags from notmuch.filename import Filenames import sys @@ -31,7 +31,8 @@ try: import simplejson as json except ImportError: import json -#------------------------------------------------------------------------------ + + class Messages(object): """Represents a list of notmuch messages @@ -63,8 +64,8 @@ class Messages(object): # However it will be kept alive until all retrieved Message() # objects are also deleted. If you do e.g. an explicit del(msgs) # here, the following lines would fail. - - # You can reiterate over *msglist* however as often as you want. + + # You can reiterate over *msglist* however as often as you want. # It is simply a list with :class:`Message`s. print (msglist[0].get_filename()) @@ -110,11 +111,11 @@ class Messages(object): (ie :class:`Query`) these tags are derived from. It saves a reference to it, so we can automatically delete the db object once all derived objects are dead. - :TODO: Make the iterator work more than once and cache the tags in + :TODO: Make the iterator work more than once and cache the tags in the Python object.(?) """ if msgs_p is None: - NotmuchError(STATUS.NULL_POINTER) + raise NotmuchError(STATUS.NULL_POINTER) self._msgs = msgs_p #store parent, so we keep them alive as long as self is alive @@ -133,7 +134,7 @@ class Messages(object): raise NotmuchError(STATUS.NOT_INITIALIZED) # collect all tags (returns NULL on error) - tags_p = Messages._collect_tags (self._msgs) + tags_p = Messages._collect_tags(self._msgs) #reset _msgs as we iterated over it and can do so only once self._msgs = None @@ -153,7 +154,7 @@ class Messages(object): self._msgs = None raise StopIteration - msg = Message(Messages._get (self._msgs), self) + msg = Message(Messages._get(self._msgs), self) nmlib.notmuch_messages_move_to_next(self._msgs) return msg @@ -167,14 +168,14 @@ class Messages(object): def __del__(self): """Close and free the notmuch Messages""" if self._msgs is not None: - nmlib.notmuch_messages_destroy (self._msgs) + nmlib.notmuch_messages_destroy(self._msgs) def print_messages(self, format, indent=0, entire_thread=False): """Outputs messages as needed for 'notmuch show' to sys.stdout :param format: A string of either 'text' or 'json'. :param indent: A number indicating the reply depth of these messages. - :param entire_thread: A bool, indicating whether we want to output + :param entire_thread: A bool, indicating whether we want to output whole threads or only the matching messages. """ if format.lower() == "text": @@ -186,7 +187,7 @@ class Messages(object): set_end = "]" set_sep = ", " else: - raise Exception + raise TypeError("format must be either 'text' or 'json'") first_set = True @@ -195,7 +196,7 @@ class Messages(object): # iterate through all toplevel messages in this thread for msg in self: # if not msg: - # break + # break if not first_set: sys.stdout.write(set_sep) first_set = False @@ -207,10 +208,8 @@ class Messages(object): if (match or entire_thread): if format.lower() == "text": sys.stdout.write(msg.format_message_as_text(indent)) - elif format.lower() == "json": - sys.stdout.write(msg.format_message_as_json(indent)) else: - raise NotmuchError + sys.stdout.write(msg.format_message_as_json(indent)) next_indent = indent + 1 # get replies and print them also out (if there are any) @@ -222,7 +221,7 @@ class Messages(object): sys.stdout.write(set_end) sys.stdout.write(set_end) -#------------------------------------------------------------------------------ + class Message(object): """Represents a single Email message @@ -236,7 +235,7 @@ class Message(object): """notmuch_message_get_filename (notmuch_message_t *message)""" _get_filename = nmlib.notmuch_message_get_filename - _get_filename.restype = c_char_p + _get_filename.restype = c_char_p """return all filenames for a message""" _get_filenames = nmlib.notmuch_message_get_filenames @@ -248,7 +247,7 @@ class Message(object): """notmuch_message_get_message_id (notmuch_message_t *message)""" _get_message_id = nmlib.notmuch_message_get_message_id - _get_message_id.restype = c_char_p + _get_message_id.restype = c_char_p """notmuch_message_get_thread_id""" _get_thread_id = nmlib.notmuch_message_get_thread_id @@ -291,17 +290,16 @@ class Message(object): objects are dead. """ if msg_p is None: - NotmuchError(STATUS.NULL_POINTER) + raise NotmuchError(STATUS.NULL_POINTER) self._msg = msg_p #keep reference to parent, so we keep it alive self._parent = parent - def get_message_id(self): """Returns the message ID - + :returns: String with a message ID - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message is not initialized. """ if self._msg is None: @@ -311,23 +309,24 @@ class Message(object): def get_thread_id(self): """Returns the thread ID - The returned string belongs to 'message' will only be valid for as + The returned string belongs to 'message' will only be valid for as long as the message is valid. This function will not return `None` since Notmuch ensures that every message belongs to a single thread. :returns: String with a thread ID - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message is not initialized. """ if self._msg is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - return Message._get_thread_id (self._msg); + return Message._get_thread_id(self._msg) def get_replies(self): - """Gets all direct replies to this message as :class:`Messages` iterator + """Gets all direct replies to this message as :class:`Messages` + iterator .. note:: This call only makes sense if 'message' was ultimately obtained from a :class:`Thread` object, (such as @@ -338,20 +337,20 @@ class Message(object): to :meth:`Query.search_messages`), then this function will return `None`. - :returns: :class:`Messages` or `None` if there are no replies to + :returns: :class:`Messages` or `None` if there are no replies to this message. - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message is not initialized. """ if self._msg is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - msgs_p = Message._get_replies(self._msg); + msgs_p = Message._get_replies(self._msg) if msgs_p is None: return None - return Messages(msgs_p,self) + return Messages(msgs_p, self) def get_date(self): """Returns time_t of the message date @@ -362,7 +361,7 @@ class Message(object): :returns: A time_t timestamp. :rtype: c_unit64 - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message is not initialized. """ if self._msg is None: @@ -370,37 +369,38 @@ class Message(object): return Message._get_date(self._msg) def get_header(self, header): - """Returns a message header - - This returns any message header that is stored in the notmuch database. - This is only a selected subset of headers, which is currently: + """Get the value of the specified header. + + The value will be read from the actual message file, not from + the notmuch database. The header name is case insensitive. - TODO: add stored headers + Returns an empty string ("") if the message does not contain a + header line matching 'header'. :param header: The name of the header to be retrieved. - It is not case-sensitive (TODO: confirm). + It is not case-sensitive. :type header: str :returns: The header value as string :exception: :exc:`NotmuchError` - * STATUS.NOT_INITIALIZED if the message + * STATUS.NOT_INITIALIZED if the message is not initialized. - * STATUS.NULL_POINTER, if no header was found + * STATUS.NULL_POINTER if any error occured. """ if self._msg is None: raise NotmuchError(STATUS.NOT_INITIALIZED) #Returns NULL if any error occurs. - header = Message._get_header (self._msg, header) + header = Message._get_header(self._msg, header) if header == None: raise NotmuchError(STATUS.NULL_POINTER) - return header + return header.decode('UTF-8') def get_filename(self): """Returns the file path of the message file :returns: Absolute file path & name of the message file - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message is not initialized. """ if self._msg is None: @@ -415,7 +415,7 @@ class Message(object): not necessarily have identical content.""" if self._msg is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - + files_p = Message._get_filenames(self._msg) return Filenames(files_p, self).as_generator() @@ -427,10 +427,10 @@ class Message(object): *Message.FLAG.MATCH* for those messages that match the query. This method allows us to get the value of this flag. - :param flag: One of the :attr:`Message.FLAG` values (currently only + :param flag: One of the :attr:`Message.FLAG` values (currently only *Message.FLAG.MATCH* :returns: An unsigned int (0/1), indicating whether the flag is set. - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message is not initialized. """ if self._msg is None: @@ -440,12 +440,12 @@ class Message(object): def set_flag(self, flag, value): """Sets/Unsets a specific flag for this message - :param flag: One of the :attr:`Message.FLAG` values (currently only + :param flag: One of the :attr:`Message.FLAG` values (currently only *Message.FLAG.MATCH* :param value: A bool indicating whether to set or unset the flag. :returns: Nothing - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message is not initialized. """ if self._msg is None: @@ -458,7 +458,7 @@ class Message(object): :returns: A :class:`Tags` iterator. :exception: :exc:`NotmuchError` - * STATUS.NOT_INITIALIZED if the message + * STATUS.NOT_INITIALIZED if the message is not initialized. * STATUS.NULL_POINTER, on error """ @@ -493,10 +493,10 @@ class Message(object): STATUS.NULL_POINTER The 'tag' argument is NULL STATUS.TAG_TOO_LONG - The length of 'tag' is too long + The length of 'tag' is too long (exceeds Message.NOTMUCH_TAG_MAX) STATUS.READ_ONLY_DATABASE - Database was opened in read-only mode so message cannot be + Database was opened in read-only mode so message cannot be modified. STATUS.NOT_INITIALIZED The message has not been initialized. @@ -504,7 +504,7 @@ class Message(object): if self._msg is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - status = nmlib.notmuch_message_add_tag (self._msg, tag) + status = nmlib.notmuch_message_add_tag(self._msg, _str(tag)) # bail out on failure if status != STATUS.SUCCESS: @@ -529,7 +529,7 @@ class Message(object): that this will do nothing when a message is frozen, as tag changes will not be committed to the database yet. - :returns: STATUS.SUCCESS if the tag was successfully removed or if + :returns: STATUS.SUCCESS if the tag was successfully removed or if the message had no such tag. Raises an exception otherwise. :exception: :exc:`NotmuchError`. They have the following meaning: @@ -540,7 +540,7 @@ class Message(object): The length of 'tag' is too long (exceeds NOTMUCH_TAG_MAX) STATUS.READ_ONLY_DATABASE - Database was opened in read-only mode so message cannot + Database was opened in read-only mode so message cannot be modified. STATUS.NOT_INITIALIZED The message has not been initialized. @@ -548,7 +548,7 @@ class Message(object): if self._msg is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - status = nmlib.notmuch_message_remove_tag(self._msg, tag) + status = nmlib.notmuch_message_remove_tag(self._msg, _str(tag)) # bail out on error if status != STATUS.SUCCESS: raise NotmuchError(status) @@ -557,8 +557,6 @@ class Message(object): self.tags_to_maildir_flags() return STATUS.SUCCESS - - def remove_all_tags(self, sync_maildir_flags=False): """Removes all tags from the given message. @@ -579,14 +577,14 @@ class Message(object): :exception: :exc:`NotmuchError`. They have the following meaning: STATUS.READ_ONLY_DATABASE - Database was opened in read-only mode so message cannot + Database was opened in read-only mode so message cannot be modified. STATUS.NOT_INITIALIZED The message has not been initialized. """ if self._msg is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - + status = nmlib.notmuch_message_remove_all_tags(self._msg) # bail out on error @@ -600,8 +598,8 @@ class Message(object): def freeze(self): """Freezes the current state of 'message' within the database - This means that changes to the message state, (via :meth:`add_tag`, - :meth:`remove_tag`, and :meth:`remove_all_tags`), will not be + This means that changes to the message state, (via :meth:`add_tag`, + :meth:`remove_tag`, and :meth:`remove_all_tags`), will not be committed to the database until the message is :meth:`thaw`ed. Multiple calls to freeze/thaw are valid and these calls will @@ -633,14 +631,14 @@ class Message(object): :exception: :exc:`NotmuchError`. They have the following meaning: STATUS.READ_ONLY_DATABASE - Database was opened in read-only mode so message cannot + Database was opened in read-only mode so message cannot be modified. STATUS.NOT_INITIALIZED The message has not been initialized. """ if self._msg is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - + status = nmlib.notmuch_message_freeze(self._msg) if STATUS.SUCCESS == status: @@ -652,7 +650,7 @@ class Message(object): def thaw(self): """Thaws the current 'message' - Thaw the current 'message', synchronizing any changes that may have + Thaw the current 'message', synchronizing any changes that may have occurred while 'message' was frozen into the notmuch database. See :meth:`freeze` for an example of how to use this @@ -667,15 +665,15 @@ class Message(object): :exception: :exc:`NotmuchError`. They have the following meaning: STATUS.UNBALANCED_FREEZE_THAW - An attempt was made to thaw an unfrozen message. - That is, there have been an unbalanced number of calls + An attempt was made to thaw an unfrozen message. + That is, there have been an unbalanced number of calls to :meth:`freeze` and :meth:`thaw`. STATUS.NOT_INITIALIZED The message has not been initialized. """ if self._msg is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - + status = nmlib.notmuch_message_thaw(self._msg) if STATUS.SUCCESS == status: @@ -684,7 +682,6 @@ class Message(object): raise NotmuchError(status) - def is_match(self): """(Not implemented)""" return self.get_flag(Message.FLAG.MATCH) @@ -697,10 +694,10 @@ class Message(object): 'P' if the message has the "passed" tag 'R' if the message has the "replied" tag 'S' if the message does not have the "unread" tag - + Any existing flags unmentioned in the list above will be preserved in the renaming. - + Also, if this filename is in a directory named "new", rename it to be within the neighboring directory named "cur". @@ -749,11 +746,10 @@ class Message(object): """A message() is represented by a 1-line summary""" msg = {} msg['from'] = self.get_header('from') - msg['tags'] = str(self.get_tags()) + msg['tags'] = self.get_tags() msg['date'] = date.fromtimestamp(self.get_date()) return "%(from)s (%(date)s) (%(tags)s)" % (msg) - def get_message_parts(self): """Output like notmuch show""" fp = open(self.get_filename()) @@ -802,7 +798,7 @@ class Message(object): part_dict["content-type"] = cont_type # NOTE: # Now we emulate the current behaviour, where it ignores - # the html if there's a text representation. + # the html if there's a text representation. # # This is being worked on, but it will be easier to fix # here in the future than to end up with another @@ -813,7 +809,7 @@ class Message(object): else: if cont_type.lower() == "text/plain": part_dict["content"] = msg.get_payload() - elif (cont_type.lower() == "text/html" and + elif (cont_type.lower() == "text/html" and i == 0): part_dict["content"] = msg.get_payload() body.append(part_dict) @@ -858,18 +854,18 @@ class Message(object): parts = format["body"] parts.sort(key=lambda x: x['id']) for p in parts: - if not p.has_key("filename"): + if not "filename" in p: output += "\n\fpart{ " - output += "ID: %d, Content-type: %s\n" % (p["id"], - p["content-type"]) - if p.has_key("content"): + output += "ID: %d, Content-type: %s\n" % (p["id"], + p["content-type"]) + if "content" in p: output += "\n%s\n" % p["content"] else: output += "Non-text part: %s\n" % p["content-type"] - output += "\n\fpart}" + output += "\n\fpart}" else: output += "\n\fattachment{ " - output += "ID: %d, Content-type:%s\n" % (p["id"], + output += "ID: %d, Content-type:%s\n" % (p["id"], p["content-type"]) output += "Attachment: %s\n" % p["filename"] output += "\n\fattachment}\n" @@ -895,7 +891,7 @@ class Message(object): been added or removed, the same messages would not be considered equal (as they do not point to the same set of files any more).""" - res = cmp(self.get_message_id(), other.get_message_id()) + res = cmp(self.get_message_id(), other.get_message_id()) if res: res = cmp(list(self.get_filenames()), list(other.get_filenames())) return res @@ -903,4 +899,4 @@ class Message(object): def __del__(self): """Close and free the notmuch Message""" if self._msg is not None: - nmlib.notmuch_message_destroy (self._msg) + nmlib.notmuch_message_destroy(self._msg) diff --git a/bindings/python/notmuch/tag.py b/bindings/python/notmuch/tag.py index e123b0f3..50e3686b 100644 --- a/bindings/python/notmuch/tag.py +++ b/bindings/python/notmuch/tag.py @@ -19,19 +19,21 @@ Copyright 2010 Sebastian Spaeth <Sebastian@SSpaeth.de>' from ctypes import c_char_p from notmuch.globals import nmlib, STATUS, NotmuchError -#------------------------------------------------------------------------------ + class Tags(object): """Represents a list of notmuch tags - This object provides an iterator over a list of notmuch tags. Do - note that the underlying library only provides a one-time iterator - (it cannot reset the iterator to the start). Thus iterating over - the function will "exhaust" the list of tags, and a subsequent + This object provides an iterator over a list of notmuch tags (which + are unicode instances). + + Do note that the underlying library only provides a one-time + iterator (it cannot reset the iterator to the start). Thus iterating + over the function will "exhaust" the list of tags, and a subsequent iteration attempt will raise a :exc:`NotmuchError` STATUS.NOT_INITIALIZED. Also note, that any function that uses iteration (nearly all) will also exhaust the tags. So both:: - for tag in tags: print tag + for tag in tags: print tag as well as:: @@ -60,7 +62,7 @@ class Tags(object): valid, we will raise an :exc:`NotmuchError` (STATUS.NULL_POINTER) if it is `None`. :type tags_p: :class:`ctypes.c_void_p` - :param parent: The parent object (ie :class:`Database` or + :param parent: The parent object (ie :class:`Database` or :class:`Message` these tags are derived from, and saves a reference to it, so we can automatically delete the db object once all derived objects are dead. @@ -68,12 +70,12 @@ class Tags(object): cache the tags in the Python object(?) """ if tags_p is None: - NotmuchError(STATUS.NULL_POINTER) + raise NotmuchError(STATUS.NULL_POINTER) self._tags = tags_p #save reference to parent object so we keep it alive self._parent = parent - + def __iter__(self): """ Make Tags an iterator """ return self @@ -81,12 +83,10 @@ class Tags(object): def next(self): if self._tags is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - # No need to call nmlib.notmuch_tags_valid(self._tags); - # Tags._get safely returns None, if there is no more valid tag. - tag = Tags._get (self._tags) - if tag is None: + if not nmlib.notmuch_tags_valid(self._tags): self._tags = None raise StopIteration + tag = Tags._get(self._tags).decode('UTF-8') nmlib.notmuch_tags_move_to_next(self._tags) return tag @@ -101,25 +101,6 @@ class Tags(object): left.""" return nmlib.notmuch_tags_valid(self._tags) > 0 - def __len__(self): - """len(:class:`Tags`) returns the number of contained tags - - .. note:: As this iterates over the tags, we will not be able - to iterate over them again (as in retrieve them)! If - the tags have been exhausted already, this will raise a - :exc:`NotmuchError` STATUS.NOT_INITIALIZED on - subsequent attempts. - """ - if self._tags is None: - raise NotmuchError(STATUS.NOT_INITIALIZED) - - i=0 - while nmlib.notmuch_tags_valid(self._msgs): - nmlib.notmuch_tags_move_to_next(self._msgs) - i += 1 - self._tags = None - return i - def __str__(self): """The str() representation of Tags() is a space separated list of tags @@ -134,4 +115,4 @@ class Tags(object): def __del__(self): """Close and free the notmuch tags""" if self._tags is not None: - nmlib.notmuch_tags_destroy (self._tags) + nmlib.notmuch_tags_destroy(self._tags) diff --git a/bindings/python/notmuch/thread.py b/bindings/python/notmuch/thread.py index 2bb30b70..5e08eb31 100644 --- a/bindings/python/notmuch/thread.py +++ b/bindings/python/notmuch/thread.py @@ -23,7 +23,7 @@ from notmuch.message import Messages from notmuch.tag import Tags from datetime import date -#------------------------------------------------------------------------------ + class Threads(object): """Represents a list of notmuch threads @@ -59,13 +59,13 @@ class Threads(object): for thread in threads: threadlist.append(thread) - # threads is "exhausted" now and even len(threads) will raise an + # threads is "exhausted" now and even len(threads) will raise an # exception. # However it will be kept around until all retrieved Thread() objects are - # also deleted. If you did e.g. an explicit del(threads) here, the + # also deleted. If you did e.g. an explicit del(threads) here, the # following lines would fail. - - # You can reiterate over *threadlist* however as often as you want. + + # You can reiterate over *threadlist* however as often as you want. # It is simply a list with Thread objects. print (threadlist[0].get_thread_id()) @@ -91,11 +91,11 @@ class Threads(object): (ie :class:`Query`) these tags are derived from. It saves a reference to it, so we can automatically delete the db object once all derived objects are dead. - :TODO: Make the iterator work more than once and cache the tags in + :TODO: Make the iterator work more than once and cache the tags in the Python object.(?) """ if threads_p is None: - NotmuchError(STATUS.NULL_POINTER) + raise NotmuchError(STATUS.NULL_POINTER) self._threads = threads_p #store parent, so we keep them alive as long as self is alive @@ -113,14 +113,14 @@ class Threads(object): self._threads = None raise StopIteration - thread = Thread(Threads._get (self._threads), self) + thread = Thread(Threads._get(self._threads), self) nmlib.notmuch_threads_move_to_next(self._threads) return thread def __len__(self): """len(:class:`Threads`) returns the number of contained Threads - .. note:: As this iterates over the threads, we will not be able to + .. note:: As this iterates over the threads, we will not be able to iterate over them again! So this will fail:: #THIS FAILS @@ -132,7 +132,7 @@ class Threads(object): if self._threads is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - i=0 + i = 0 # returns 'bool'. On out-of-memory it returns None while nmlib.notmuch_threads_valid(self._threads): nmlib.notmuch_threads_move_to_next(self._threads) @@ -143,7 +143,7 @@ class Threads(object): def __nonzero__(self): """Check if :class:`Threads` contains at least one more valid thread - + The existence of this function makes 'if Threads: foo' work, as that will implicitely call len() exhausting the iterator if __nonzero__ does not exist. This function makes `bool(Threads())` @@ -158,9 +158,9 @@ class Threads(object): def __del__(self): """Close and free the notmuch Threads""" if self._threads is not None: - nmlib.notmuch_messages_destroy (self._threads) + nmlib.notmuch_messages_destroy(self._threads) + -#------------------------------------------------------------------------------ class Thread(object): """Represents a single message thread.""" @@ -206,7 +206,7 @@ class Thread(object): objects are dead. """ if thread_p is None: - NotmuchError(STATUS.NULL_POINTER) + raise NotmuchError(STATUS.NULL_POINTER) self._thread = thread_p #keep reference to parent, so we keep it alive self._parent = parent @@ -218,7 +218,7 @@ class Thread(object): for as long as the thread is valid. :returns: String with a message ID - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the thread + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the thread is not initialized. """ if self._thread is None: @@ -231,14 +231,13 @@ class Thread(object): :returns: The number of all messages in the database belonging to this thread. Contrast with :meth:`get_matched_messages`. - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the thread + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the thread is not initialized. """ if self._thread is None: raise NotmuchError(STATUS.NOT_INITIALIZED) return nmlib.notmuch_thread_get_total_messages(self._thread) - def get_toplevel_messages(self): """Returns a :class:`Messages` iterator for the top-level messages in 'thread' @@ -246,7 +245,7 @@ class Thread(object): This iterator will not necessarily iterate over all of the messages in the thread. It will only iterate over the messages in the thread which are not replies to other messages in the thread. - + To iterate over all messages in the thread, the caller will need to iterate over the result of :meth:`Message.get_replies` for each top-level message (and do that recursively for the resulting @@ -256,7 +255,7 @@ class Thread(object): :exception: :exc:`NotmuchError` * STATUS.NOT_INITIALIZED if query is not inited - * STATUS.NULL_POINTER if search_messages failed + * STATUS.NULL_POINTER if search_messages failed """ if self._thread is None: raise NotmuchError(STATUS.NOT_INITIALIZED) @@ -264,17 +263,17 @@ class Thread(object): msgs_p = Thread._get_toplevel_messages(self._thread) if msgs_p is None: - NotmuchError(STATUS.NULL_POINTER) + raise NotmuchError(STATUS.NULL_POINTER) - return Messages(msgs_p,self) + return Messages(msgs_p, self) def get_matched_messages(self): """Returns the number of messages in 'thread' that matched the query - :returns: The number of all messages belonging to this thread that + :returns: The number of all messages belonging to this thread that matched the :class:`Query`from which this thread was created. Contrast with :meth:`get_total_messages`. - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the thread + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the thread is not initialized. """ if self._thread is None: @@ -288,29 +287,35 @@ class Thread(object): authors of mail messages in the query results that belong to this thread. - The returned string belongs to 'thread' and will only be valid for + The returned string belongs to 'thread' and will only be valid for as long as this Thread() is not deleted. """ if self._thread is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - return Thread._get_authors(self._thread) + authors = Thread._get_authors(self._thread) + if authors is None: + return None + return authors.decode('UTF-8') def get_subject(self): """Returns the Subject of 'thread' - The returned string belongs to 'thread' and will only be valid for + The returned string belongs to 'thread' and will only be valid for as long as this Thread() is not deleted. """ if self._thread is None: raise NotmuchError(STATUS.NOT_INITIALIZED) - return Thread._get_subject(self._thread) + subject = Thread._get_subject(self._thread) + if subject is None: + return None + return subject.decode('UTF-8') def get_newest_date(self): """Returns time_t of the newest message date :returns: A time_t timestamp. :rtype: c_unit64 - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message is not initialized. """ if self._thread is None: @@ -322,7 +327,7 @@ class Thread(object): :returns: A time_t timestamp. :rtype: c_unit64 - :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message + :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message is not initialized. """ if self._thread is None: @@ -337,14 +342,14 @@ class Thread(object): tags of the messages which matched the search and which belong to this thread. - The :class:`Tags` object is owned by the thread and as such, will only - be valid for as long as this :class:`Thread` is valid (e.g. until the + The :class:`Tags` object is owned by the thread and as such, will only + be valid for as long as this :class:`Thread` is valid (e.g. until the query from which it derived is explicitely deleted). :returns: A :class:`Tags` iterator. :exception: :exc:`NotmuchError` - * STATUS.NOT_INITIALIZED if the thread + * STATUS.NOT_INITIALIZED if the thread is not initialized. * STATUS.NULL_POINTER, on error """ @@ -355,7 +360,7 @@ class Thread(object): if tags_p == None: raise NotmuchError(STATUS.NULL_POINTER) return Tags(tags_p, self) - + def __str__(self): """A str(Thread()) is represented by a 1-line summary""" thread = {} @@ -374,9 +379,15 @@ class Thread(object): thread['subject'] = self.get_subject() thread['tags'] = self.get_tags() - return "thread:%(id)s %(date)12s [%(matched)d/%(total)d] %(authors)s; %(subject)s (%(tags)s)" % (thread) + return "thread:%s %12s [%d/%d] %s; %s (%s)" % (thread['id'], + thread['date'], + thread['matched'], + thread['total'], + thread['authors'], + thread['subject'], + thread['tags']) def __del__(self): """Close and free the notmuch Thread""" if self._thread is not None: - nmlib.notmuch_thread_destroy (self._thread) + nmlib.notmuch_thread_destroy(self._thread) diff --git a/bindings/python/notmuch/version.py b/bindings/python/notmuch/version.py new file mode 100644 index 00000000..fd414b0a --- /dev/null +++ b/bindings/python/notmuch/version.py @@ -0,0 +1,2 @@ +# this file should be kept in sync with ../../../version +__VERSION__ = '0.10.2' diff --git a/bindings/python/setup.py b/bindings/python/setup.py index 1497bc43..286fd196 100644 --- a/bindings/python/setup.py +++ b/bindings/python/setup.py @@ -4,18 +4,11 @@ import os import re from distutils.core import setup -def get_version(): - file = open('notmuch/__init__.py') - try: - for line in file: - if re.match('__VERSION__\s*=\s*',line) != None: - version = line.split('=', 1)[1] - return eval(version, {}, {}) - finally: - file.close() - raise IOError('Unexpected end-of-file') - -__VERSION__=get_version() +# get the notmuch version number without importing the notmuch module +version_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), + 'notmuch', 'version.py') +execfile(version_file) +assert __VERSION__, 'Failed to read the notmuch binding version number' setup(name='notmuch', version=__VERSION__, @@ -53,12 +46,11 @@ left of cnotmuch then. Requirements ------------ -You need to have notmuch installed (or rather libnotmuch.so.1). The -release version 0.3 should work fine. Also, notmuch makes use of the -ctypes library, and has only been tested with python 2.5. It will not -work on earlier python versions. +You need to have notmuch installed (or rather libnotmuch.so.1). Also, +notmuch makes use of the ctypes library, and has only been tested with +python >= 2.5. It will not work on earlier python versions. """, - classifiers=['Development Status :: 2 - Pre-Alpha', + classifiers=['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Programming Language :: Python :: 2', |
