#!/usr/bin/env python """ Very trivial mbox sorting tool that invokes $EDITOR with a list of entries from an arbitrary header line across all the messages and then sorts the mbox in the order you put those header lines into. GPLv2 since it needs licensing. """ import sys, os from mailbox import mbox from email.parser import Parser import tempfile from shutil import rmtree if len(sys.argv) != 3: print "Usage: %s " % sys.argv[0] print "Example: %s Subject /tmp/patches.mbox" % sys.argv[0] print " Then, $EDITOR is invoked, you sort the subjects in" print " any order you like, and this tool sorts the mbox." sys.exit(2) m = mbox(sys.argv[2]) keys = [] messages = {} for key, msg in m.iteritems(): messages[key] = msg keys.append(key) subjects = [] subjrev = {} for (key, msg) in messages.iteritems(): msg = Parser().parsestr(str(msg)) subj = msg[sys.argv[1]] subj = subj.replace('\n ', '') subj = subj.replace('\n\t', '') subjects.append((key, subj)) subjrev[subj] = key tmpdir = tempfile.mkdtemp() try: ofn = tmpdir + '/order' order = file(ofn, 'w') for key, subj in subjects: order.write(subj + '\n') order.close() os.system('$EDITOR %s' % ofn) sorted = [] for subj in file(ofn): subj = subj[:-1] sorted.append(subjrev[subj]) if sorted != keys: for key, msg in messages.iteritems(): del m[key] for key in sorted: m.add(messages[key]) m.flush() finally: rmtree(tmpdir)