def to_maildir_flags(self): """Update the message's maildir flags based on the notmuch tags. If the message's filename is in a maildir directory, that is a directory named ``new`` or ``cur``, and has a valid maildir filename then the flags will be added as such: 'D' if the message has the "draft" tag 'F' if the message has the "flagged" tag '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". In case there are multiple files associated with the message all filenames will get the same logic applied. """ ret = capi.lib.notmuch_message_tags_to_maildir_flags(self._ptr()) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret)
def from_maildir_flags(self): """Update the tags based on the state in the message's maildir flags. This function examines the filenames of 'message' for maildir flags, and adds or removes tags on 'message' as follows when these flags are present: Flag Action if present ---- ----------------- 'D' Adds the "draft" tag to the message 'F' Adds the "flagged" tag to the message 'P' Adds the "passed" tag to the message 'R' Adds the "replied" tag to the message 'S' Removes the "unread" tag from the message For each flag that is not present, the opposite action (add/remove) is performed for the corresponding tags. Flags are identified as trailing components of the filename after a sequence of ":2,". If there are multiple filenames associated with this message, the flag is considered present if it appears in one or more filenames. (That is, the flags from the multiple filenames are combined with the logical OR operator.) """ ret = capi.lib.notmuch_message_maildir_flags_to_tags(self._ptr()) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret)
def count_threads(self): """Return the number of threads matching this query.""" count_p = capi.ffi.new('unsigned int *') ret = capi.lib.notmuch_query_count_threads(self._query_p, count_p) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) return count_p[0]
def default_path(cfg_path=None): """Return the path of the user's default database. This reads the user's configuration file and returns the default path of the database. :param cfg_path: The pathname of the notmuch configuration file. If not specified tries to use the pathname provided in the :env:`NOTMUCH_CONFIG` environment variable and falls back to :file:`~/.notmuch-config. :type cfg_path: str, bytes, os.PathLike or pathlib.Path. :returns: The path of the database, which does not necessarily exists. :rtype: pathlib.Path :raises OSError: or subclasses if the configuration file can not be opened. :raises configparser.Error: or subclasses if the configuration file can not be parsed. :raises NotmuchError if the config file does not have the database.path setting. """ if not cfg_path: cfg_path = _config_pathname() if not hasattr(os, 'PathLike') and isinstance(cfg_path, pathlib.Path): cfg_path = bytes(cfg_path) parser = configparser.ConfigParser() with open(cfg_path) as fp: parser.read_file(fp) try: return pathlib.Path(parser.get('database', 'path')) except configparser.Error: raise errors.NotmuchError( 'No database.path setting in {}'.format(cfg_path))
def threads(self): """Return an iterator over all the threads found by the query.""" threads_pp = capi.ffi.new('notmuch_threads_t **') ret = capi.lib.notmuch_query_search_threads(self._query_p, threads_pp) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) return thread.ThreadIter(self, threads_pp[0], db=self._db)
def remove(self, filename): """Remove a message from the notmuch database. Removing a message which is not in the database is just a silent nop-operation. :param filename: The pathname of the file containing the message to be removed. :type filename: str, bytes, os.PathLike or pathlib.Path. :returns: True if the message is still in the database. This can happen when multiple files contain the same message ID. The true/false distinction is fairly arbitrary, but think of it as ``dup = db.remove_message(name); if dup: ...``. :rtype: bool :raises XapianError: A Xapian exception occurred. :raises ReadOnlyDatabaseError: The database is opened in READ_ONLY mode. :raises UpgradeRequiredError: The database must be upgraded first. :raises ObjectDestroyedError: if used after destroyed. """ if not hasattr(os, 'PathLike') and isinstance(filename, pathlib.Path): filename = bytes(filename) ret = capi.lib.notmuch_database_remove_message(self._db_p, os.fsencode(filename)) ok = [capi.lib.NOTMUCH_STATUS_SUCCESS, capi.lib.NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID] if ret not in ok: raise errors.NotmuchError(ret) if ret == capi.lib.NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID: return True else: return False
def __delitem__(self, key): """Remove all properties with this key.""" if isinstance(key, str): key = key.encode('utf-8') ret = capi.lib.notmuch_message_remove_all_properties(self._ptr(), key) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret)
def get(self, filename): """Return the :class:`Message` given a pathname. If a message with the given pathname exists in the database return the :class:`Message` instance for the message. Otherwise raise a :exc:`LookupError` exception. :param filename: The pathname of the message. :type filename: str, bytes, os.PathLike or pathlib.Path :returns: The message instance. :rtype: Message :raises LookupError: If no message was found. This is also a subclass of :exc:`KeyError`. :raises OutOfMemoryError: When there is no memory to allocate the message instance. :raises XapianError: A Xapian exception occurred. :raises ObjectDestroyedError: if used after destroyed. """ if not hasattr(os, 'PathLike') and isinstance(filename, pathlib.Path): filename = bytes(filename) msg_pp = capi.ffi.new('notmuch_message_t **') ret = capi.lib.notmuch_database_find_message_by_filename( self._db_p, os.fsencode(filename), msg_pp) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) msg_p = msg_pp[0] if msg_p == capi.ffi.NULL: raise LookupError msg = message.Message(self, msg_p, db=self) return msg
def find(self, msgid): """Return the message matching the given message ID. If a message with the given message ID is found a :class:`Message` instance is returned. Otherwise a :exc:`LookupError` is raised. :param msgid: The message ID to look for. :type msgid: str :returns: The message instance. :rtype: Message :raises LookupError: If no message was found. :raises OutOfMemoryError: When there is no memory to allocate the message instance. :raises XapianError: A Xapian exception occurred. :raises ObjectDestroyedError: if used after destroyed. """ msg_pp = capi.ffi.new('notmuch_message_t **') ret = capi.lib.notmuch_database_find_message(self._db_p, msgid.encode(), msg_pp) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) msg_p = msg_pp[0] if msg_p == capi.ffi.NULL: raise LookupError msg = message.Message(self, msg_p, db=self) return msg
def add(self, tag): """Add a tag to the message. :param tag: The tag to add. :type tag: str or bytes. A str will be encoded using UTF-8. :param sync_flags: Whether to sync the maildir flags with the new set of tags. Leaving this as *None* respects the configuration set in the database, while *True* will always sync and *False* will never sync. :param sync_flags: NoneType or bool :raises TypeError: If the tag is not a valid type. :raises TagTooLongError: If the added tag exceeds the maximum length, see ``notmuch_cffi.NOTMUCH_TAG_MAX``. :raises ReadOnlyDatabaseError: If the database is opened in read-only mode. """ if isinstance(tag, str): tag = tag.encode() if not isinstance(tag, bytes): raise TypeError('Not a valid type for a tag: {}'.format(type(tag))) ret = capi.lib.notmuch_message_add_tag(self._ptr(), tag) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret)
def __setitem__(self, key, val): if isinstance(key, str): key = key.encode('utf-8') if isinstance(val, str): val = val.encode('utf-8') ret = capi.lib.notmuch_database_set_config(self._ptr(), key, val) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret)
def create(cls, path=None, config=ConfigFile.EMPTY): """Create and open database in READ_WRITE mode. This is creates a new notmuch database and returns an opened instance in :attr:`MODE.READ_WRITE` mode. :param path: The directory of where the database is stored. If ``None`` the location will be read searched by the notmuch library (see notmuch(3)::notmuch_open_with_config). :type path: str, bytes or os.PathLike :param config: The pathname of the notmuch configuration file. :type config: :attr:`CONFIG.EMPTY`, :attr:`CONFIG.SEARCH`, str, bytes, os.PathLike, pathlib.Path :raises OSError: or subclasses if the configuration file can not be opened. :raises configparser.Error: or subclasses if the configuration file can not be parsed. :raises NotmuchError: if the config file does not have the database.path setting. :raises FileError: if the database already exists. :returns: The newly created instance. """ db_pp = capi.ffi.new('notmuch_database_t **') cmsg = capi.ffi.new('char**') ret = capi.lib.notmuch_database_create_with_config(cls._db_path_encode(path), cls._cfg_path_encode(config), capi.ffi.NULL, db_pp, cmsg) if cmsg[0]: msg = capi.ffi.string(cmsg[0]).decode(errors='replace') capi.lib.free(cmsg[0]) else: msg = None if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret, msg) # Now close the db and let __init__ open it. Inefficient but # creating is not a hot loop while this allows us to have a # clean API. ret = capi.lib.notmuch_database_destroy(db_pp[0]) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) return cls(path, cls.MODE.READ_WRITE, config=config)
def add(self, filename, *, sync_flags=False, indexopts=None): """Add a message to the database. Add a new message to the notmuch database. The message is referred to by the pathname of the maildir file. If the message ID of the new message already exists in the database, this adds ``pathname`` to the list of list of files for the existing message. :param filename: The path of the file containing the message. :type filename: str, bytes, os.PathLike or pathlib.Path. :param sync_flags: Whether to sync the known maildir flags to notmuch tags. See :meth:`Message.flags_to_tags` for details. :type sync_flags: bool :param indexopts: The indexing options, see :meth:`default_indexopts`. Leave as `None` to use the default options configured in the database. :type indexopts: :class:`IndexOptions` or `None` :returns: A tuple where the first item is the newly inserted messages as a :class:`Message` instance, and the second item is a boolean indicating if the message inserted was a duplicate. This is the namedtuple ``AddedMessage(msg, dup)``. :rtype: Database.AddedMessage If an exception is raised, no message was added. :raises XapianError: A Xapian exception occurred. :raises FileError: The file referred to by ``pathname`` could not be opened. :raises FileNotEmailError: The file referreed to by ``pathname`` is not recognised as an email message. :raises ReadOnlyDatabaseError: The database is opened in READ_ONLY mode. :raises UpgradeRequiredError: The database must be upgraded first. :raises ObjectDestroyedError: if used after destroyed. """ if not hasattr(os, 'PathLike') and isinstance(filename, pathlib.Path): filename = bytes(filename) msg_pp = capi.ffi.new('notmuch_message_t **') opts_p = indexopts._opts_p if indexopts else capi.ffi.NULL ret = capi.lib.notmuch_database_index_file(self._db_p, os.fsencode(filename), opts_p, msg_pp) ok = [ capi.lib.NOTMUCH_STATUS_SUCCESS, capi.lib.NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID ] if ret not in ok: raise errors.NotmuchError(ret) msg = message.Message(self, msg_pp[0], db=self) if sync_flags: msg.tags.from_maildir_flags() return self.AddedMessage( msg, ret == capi.lib.NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID)
def create(cls, path=None): """Create and open database in READ_WRITE mode. This is creates a new notmuch database and returns an opened instance in :attr:`MODE.READ_WRITE` mode. :param path: The directory of where the database is stored. If ``None`` the location will be read from the user's configuration file, respecting the ``NOTMUCH_CONFIG`` environment variable if set. :type path: str, bytes or os.PathLike :raises OSError: or subclasses if the configuration file can not be opened. :raises configparser.Error: or subclasses if the configuration file can not be parsed. :raises NotmuchError: if the config file does not have the database.path setting. :raises FileError: if the database already exists. :returns: The newly created instance. """ if path is None: path = cls.default_path() if not hasattr(os, 'PathLike') and isinstance(path, pathlib.Path): path = bytes(path) db_pp = capi.ffi.new('notmuch_database_t **') cmsg = capi.ffi.new('char**') ret = capi.lib.notmuch_database_create_verbose(os.fsencode(path), db_pp, cmsg) if cmsg[0]: msg = capi.ffi.string(cmsg[0]).decode(errors='replace') capi.lib.free(cmsg[0]) else: msg = None if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret, msg) # Now close the db and let __init__ open it. Inefficient but # creating is not a hot loop while this allows us to have a # clean API. ret = capi.lib.notmuch_database_destroy(db_pp[0]) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) return cls(path, cls.MODE.READ_WRITE)
def clear(self): """Remove all tags from the message. :raises ReadOnlyDatabaseError: If the database is opened in read-only mode. """ ret = capi.lib.notmuch_message_remove_all_tags(self._ptr()) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret)
def remove(self, key, value): """Remove a key-value pair from the properties.""" if isinstance(key, str): key = key.encode('utf-8') if isinstance(value, str): value = value.encode('utf-8') ret = capi.lib.notmuch_message_remove_property(self._ptr(), key, value) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret)
def _destroy(self): try: ret = capi.lib.notmuch_database_destroy(self._db_p) except errors.ObjectDestroyedError: ret = capi.lib.NOTMUCH_STATUS_SUCCESS else: self._db_p = None if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret)
def frozen(self): """Context manager to freeze the message state. This allows you to perform atomic tag updates:: with msg.frozen(): msg.tags.clear() msg.tags.add('foo') Using This would ensure the message never ends up with no tags applied at all. It is safe to nest calls to this context manager. :raises ReadOnlyDatabaseError: if the database is opened in read-only mode. :raises UnbalancedFreezeThawError: if you somehow managed to call __exit__ of this context manager more than once. Why did you do that? :raises ObjectDestroyedError: if used after destroyed. """ ret = capi.lib.notmuch_message_freeze(self._msg_p) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) self._frozen = True try: yield except Exception: # Only way to "rollback" these changes is to destroy # ourselves and re-create. Behold. msgid = self.messageid self._destroy() with contextlib.suppress(Exception): new = self._db.find(msgid) self._msg_p = new._msg_p new._msg_p = None del new raise else: ret = capi.lib.notmuch_message_thaw(self._msg_p) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) self._frozen = False
def __iter__(self): """Return an iterator over the config items. :raises NullPointerError: If the iterator can not be created. """ configlist_pp = capi.ffi.new('notmuch_config_list_t**') ret = capi.lib.notmuch_database_get_config_list(self._ptr(), b'', configlist_pp) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) return ConfigIter(self._parent, configlist_pp[0])
def collect_tags(self): """Return the tags of messages matching this query.""" msgs_pp = capi.ffi.new('notmuch_messages_t**') ret = capi.lib.notmuch_query_search_messages(self._query_p, msgs_pp) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) self._msgs_p = msgs_pp[0] tagset = tags.ImmutableTagSet(self, '_msgs_p', capi.lib.notmuch_messages_collect_tags) return tags.ImmutableTagSet._from_iterable(tagset)
def messages(self): """Return an iterator over all the messages found by the query. This executes the query and returns an iterator over the :class:`Message` objects found. """ msgs_pp = capi.ffi.new('notmuch_messages_t**') ret = capi.lib.notmuch_query_search_messages(self._query_p, msgs_pp) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) return message.MessageIter(self, msgs_pp[0], db=self._db)
def __getitem__(self, key): """Return **the first** peroperty associated with a key.""" if isinstance(key, str): key = key.encode('utf-8') value_pp = capi.ffi.new('char**') ret = capi.lib.notmuch_message_get_property(self._ptr(), key, value_pp) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) if value_pp[0] == capi.ffi.NULL: raise KeyError return base.BinString.from_cffi(value_pp[0])
def __getitem__(self, key): if isinstance(key, str): key = key.encode('utf-8') val_pp = capi.ffi.new('char**') ret = capi.lib.notmuch_database_get_config(self._ptr(), key, val_pp) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) val = base.BinString.from_cffi(val_pp[0]) capi.lib.free(val_pp[0]) if val == '': raise KeyError return val
def close(self): """Close the notmuch database. Once closed most operations will fail. This can still be useful however to explicitly close a database which is opened read-write as this would otherwise stop other processes from reading the database while it is open. :raises ObjectDestroyedError: if used after destroyed. """ ret = capi.lib.notmuch_database_close(self._db_p) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) self.closed = True
def force_end(self): """Force ending the atomic section. This can only be called once __exit__ has been called. It will attempt to close the atomic section (again). This is useful if the original exit raised an exception and the atomic section is still open. But things are pretty ugly by now. :raises XapianError: If exiting fails, the atomic section is not ended. :raises UnbalancedAtomicError: If the database was currently not in an atomic section. :raises ObjectDestroyedError: if used after destroyed. """ ret = capi.lib.notmuch_database_end_atomic(self._ptr()) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret)
def __init__(self, path=None, mode=MODE.READ_ONLY, config=CONFIG.SEARCH): if isinstance(mode, str): mode = self.STR_MODE_MAP[mode] self.mode = mode db_pp = capi.ffi.new('notmuch_database_t **') cmsg = capi.ffi.new('char**') ret = capi.lib.notmuch_database_open_with_config( self._db_path_encode(path), mode.value, self._cfg_path_encode(config), capi.ffi.NULL, db_pp, cmsg) if cmsg[0]: msg = capi.ffi.string(cmsg[0]).decode(errors='replace') capi.lib.free(cmsg[0]) else: msg = None if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret, msg) self._db_p = db_pp[0] self.closed = False
def __init__(self, path=None, mode=MODE.READ_ONLY): if isinstance(mode, str): mode = self.STR_MODE_MAP[mode] self.mode = mode if path is None: path = self.default_path() if not hasattr(os, 'PathLike') and isinstance(path, pathlib.Path): path = bytes(path) db_pp = capi.ffi.new('notmuch_database_t **') cmsg = capi.ffi.new('char**') ret = capi.lib.notmuch_database_open_verbose(os.fsencode(path), mode.value, db_pp, cmsg) if cmsg[0]: msg = capi.ffi.string(cmsg[0]).decode(errors='replace') capi.lib.free(cmsg[0]) else: msg = None if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret, msg) self._db_p = db_pp[0] self.closed = False
def decrypt_policy(self, val): ret = capi.lib.notmuch_indexopts_set_decrypt_policy( self._opts_p, val.value) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret, msg)
def _end_atomic(self): ret = capi.lib.notmuch_database_end_atomic(self._ptr()) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret)
def __enter__(self): ret = capi.lib.notmuch_database_begin_atomic(self._ptr()) if ret != capi.lib.NOTMUCH_STATUS_SUCCESS: raise errors.NotmuchError(ret) self._exit_fn = self._end_atomic return self