#!/usr/bin/env python # # Grab email from a gmail label and write it in a local dir # # Author: tomeu@sugarlabs.org # Based on code by: ted@tedkulp.com # Based on code by: follower@myrealbox.com # # License: GPL 2.0 # import os import sys from getpass import getpass import re import email import subprocess import time import libgmail PATCHES_LABEL = 'Patches' PATCHES_DIR = os.path.expanduser('~/patches') def _may_be_patch(message): found_minuses = False for line in message.source.split('\n'): if found_minuses and line.startswith('+++'): return True if line.startswith('---'): found_minuses = True else: found_minuses = False return False def _write_patch(message): if not os.path.exists(PATCHES_DIR): os.mkdir(PATCHES_DIR) full_message = message.source.replace('\r', '').strip().encode('utf-8') email_message = email.message_from_string(full_message) subject = email_message['Subject'].replace('\n\t', ' ') # TODO: Probably should remove all tags between [], what does git-am? subject = subject.replace('[Sugar-devel] ', '') subject = subject.replace('[PATCH] ', '') file_path = subject.replace(' ', '-') file_path += '.patch' file_path = os.path.join(PATCHES_DIR, file_path) print "Writing patch: %s" % file_path patch_file = open(file_path, 'w+') patch_file.write(full_message) patch_file.close() sent_date = time.mktime(email.utils.parsedate(email_message['Date'])) os.utime(file_path, (sent_date, sent_date)) if __name__ == "__main__": call_args = ['git', 'config', 'user.gmail'] pipe = subprocess.Popen(call_args, stdout=subprocess.PIPE) user_name = pipe.communicate()[0].strip() if not user_name: print 'Need a user name configured in .gitconfig: ' \ 'git config --global user.gmail @gmail.com' exit(0) password = getpass('Password: ') ga = libgmail.GmailAccount(user_name, password) print "Please wait, logging in as %s..." % user_name try: ga.login() except libgmail.GmailLoginFailure: print "Login failed. (Wrong username/password?)" sys.exit(2) else: print "Log in successful" query = 'label: %s' % PATCHES_LABEL if len(sys.argv) > 1: query += ' %s' % sys.argv[1] result = ga.getMessagesByQuery(query, True) if len(result): for thread in reversed(result): for msg in reversed(thread): if _may_be_patch(msg): _write_patch(msg) else: print "No threads found in `%s`." % new_label