import notmuch import re import os, errno maildirish= re.compile(r"^(draft|flagged|passed|replied|unread)$") symlink = False # some random person on stack overflow suggests: def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise CHARSET=('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+_@=.,-') encode_re='([^{0}])'.format(CHARSET) def encode_one_char(match): return('%{:02x}'.format(ord(match.group(1)))) def encode_for_fs(str): return re.sub(encode_re,encode_one_char, str,0) flagre = re.compile("(:2,[^:]*)$"); tagroot='tags' db = notmuch.Database(mode=notmuch.Database.MODE.READ_ONLY) q_new = notmuch.Query(db, '*') q_new.set_sort(notmuch.Query.SORT.UNSORTED) for msg in q_new.search_messages(): for tag in msg.get_tags(): if tag == '': print 'Dunno what to do about empty tag on ', msg.get_message_id() else: if not maildirish.match(tag): # ignore multiple filenames filename = msg.get_filename() message_id = msg.get_message_id() flagsmatch = flagre.search(filename) if flagsmatch == None: flags = '' else: flags = flagsmatch.group(1) tagdir = os.path.join(tagroot, encode_for_fs(tag)) curdir = os.path.join(tagdir, 'cur') mkdir_p (os.path.join(tagdir, 'new')) mkdir_p ( os.path.join(tagdir, 'tmp')) mkdir_p(curdir); newlink = os.path.join(curdir, encode_for_fs(message_id) + flags) if symlink: os.symlink(filename, newlink) else: os.link(filename, newlink )