#!/usr/bin/python

# replace_in_file.py
#       --copyright--                   Copyright 2007 (C) Tranzoa, Co. All rights reserved.    Warranty: You're free and on your own here. This code is not necessarily up-to-date or of public quality.
#       --url--                         http://www.tranzoa.net/tzpython/
#       --email--                       pycode is the name to send to. tranzoa.com is the place to send to.
#       --bodstamps--
#       June 2, 2004            bar
#       November 18, 2007       bar     turn on doxygen
#       November 27, 2007       bar     insert boilerplate copyright
#       May 17, 2008            bar     email adr
#       November 29, 2011       bar     pyflake cleanup
#       --eodstamps--
##      \file
#
#
#       Update a file, replacing some text between two instances of a string.
#
#


import  re

import  replace_file


__all__     = [
                'replace_in_text',
                'replace_in_file',
                'replace_file_in_file',
              ]


def replace_in_text(text,      match_text, replacement_text) :
    """
        Replace anything between pairs of instances of 'match_text' in 'text' with 'replacement_text'.

        Return None if no replacement is done.
        Return the modified string, if a replacement was made.
    """

    ms = re.escape(match_text) + ".*" + re.escape(match_text)
    m = re.compile(ms, re.DOTALL)

    s = m.subn(match_text + "\n" + replacement_text + "\n" + match_text, text)
    if  s[1] == 0 :
        return(None)

    return(s[0])




def replace_in_file(file_name, match_text, replacement_text) :
    """
        Update a file, replacing any text between pairs of instances of 'match_text' with 'replacement_text'.

        Return True/False whether a replacement was made.
    """

    f    = open(file_name, "rb")
    text = f.read()
    f.close()

    text = replace_in_text(text, match_text, replacement_text)
    if  text != None :
        f = open(file_name + ".tmp", "wb")
        f.write(text)
        f.close()

        replace_file.replace_file(file_name, file_name + ".tmp", file_name + ".bak")

        return(True)

    return(False)



def replace_file_in_file(file_name, match_text, replacement_file) :
    f    = open(replacement_file, "rb")
    text = f.read()
    f.close()

    return(replace_in_file(file_name, match_text, text))



#
#
#
if __name__ == '__main__' :
    import  sys

    if  len(sys.argv) != 4 :
        print "Tell me a file name, marker text, and replacement file name."
    else :
        replace_file_in_file(sys.argv[1], sys.argv[2], sys.argv[3])
    pass


#
#
#
# eof

