#!/usr/bin/env python import logging import os import re import sre_constants import subprocess import sys import tempfile LOG_FORMAT = '%(asctime)-15s %(message)s' LOG_LEVEL = logging.DEBUG LOGGER = None def setupLogging(): global LOGGER if not LOGGER: logging.basicConfig(format=LOG_FORMAT, level=LOG_LEVEL) LOGGER = logging.getLogger('gcooper-pr-editor') def info(fmt, *args, **kwargs): global LOGGER setupLogging() LOGGER.info(fmt, *args, **kwargs) def warning(fmt, *args, **kwargs): global LOGGER setupLogging() LOGGER.warning(fmt, *args, **kwargs) def error(fmt, *args, **kwargs): global LOGGER setupLogging() LOGGER.error(fmt, *args, **kwargs) sys.exit(1) def SetUserEmail(file_path, user_name, user_mail): '''Change the email address of a user in file 'file_path'. Edit a file at 'file_path' in place, and replace the email address in lines that match the pattern: User Name with the new email address specified as 'user_mail'. Args: file_path (str) The path of the file to edit. user_name (str) The name of the user to search for. Only lines that contain both this user name *and* an email address, enclosed in <> characters, are affected. user_mail (str) The new email address to use for lines that match the user's name. ''' info('Preparing match/replace patterns') match_pattern = '' matcher = None try: match_pattern = r'^.*\b(%s)\s*<(\S+)>.*$' % (user_name) replace_pattern = r'%s\s*<\S+>' % (user_name) replace_text = '%s <%s>' % (user_name, user_mail) matcher = re.compile(match_pattern) except sre_constants.error, e: error('Cannot compile match/replace patterns', match_pattern) return None info('Match pattern = "%s"', match_pattern) info('Replace pattern = "%s"', replace_pattern) info('Replacement text = "%s"', replace_text) try: (fd, ftemp_path) = tempfile.mkstemp() ftemp = os.fdopen(fd, 'w+') with file(file_path) as finput: for line in finput.readlines(): text = line m = matcher.match(line) if m: text = re.sub(replace_pattern, replace_text, line) ftemp.write(text) ftemp.flush() info('Input file copied at %s', ftemp_path) cmd = [ 'diff', '-u', file_path, ftemp_path ] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE) info('Changes applied:') for line in proc.stdout: info(' %s', line.rstrip()) ftemp.close() info('Replacing file %s with %s', file_path, ftemp_path) os.rename(ftemp_path, file_path) except IOError, e: error('Cannot edit input file at %s -- %s', file_path, str(e)) return None if __name__ == '__main__': setupLogging() user_name = 'Garrett Cooper' user_mail = 'yaneurabeya@gmail.com' for filename in sys.argv[1:]: SetUserEmail(filename, user_name, user_mail)