Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036 import os
00037 import re
00038 import time
00039 import ezt
00040 import StringIO
00041
00042 class gen_base:
00043
00044 def check_overwrite(self, fname):
00045 """
00046 Check file exist or not.
00047 """
00048 msg = " already exists. Overwrite or merge? (y/n/m)"
00049 if (os.access(fname, os.F_OK)):
00050 ans = raw_input("\"" + fname + "\"" + msg)
00051 if (ans == "y" or ans == "Y"):
00052 return file(fname, "w"), None
00053 elif (ans == "m" or ans == "M"):
00054 f = file(fname, "r")
00055 lines = []
00056 for l in f.readlines():
00057 lines.append(l.rstrip())
00058 f.close()
00059 oldfname = fname + ".old." + time.strftime("%y%m%d%H%M%S")
00060 os.rename(fname, oldfname)
00061 return file(fname, "w"), lines
00062 else:
00063 return None, None
00064 else:
00065 return file(fname, "w"), None
00066 return
00067
00068 def replace_tags(self, lines, data):
00069 in_tag = False
00070 tag_name = ""
00071 ret_lines = ""
00072
00073 for l in lines:
00074 m = re.search("<rtc-template block=\"(.*?)\">", l)
00075 if m:
00076 in_tag = True
00077 tag_name = m.group(1)
00078 ret_lines += l + "\n"
00079 continue
00080
00081 m = re.search("</rtc-template>", l)
00082 if m:
00083 in_tag = False
00084 if data.has_key(tag_name):
00085 ret_lines += data[tag_name] + "\n"
00086 ret_lines += l + "\n"
00087 tag_name = ""
00088 continue
00089
00090 if in_tag != True:
00091 ret_lines += l + "\n"
00092
00093 return ret_lines
00094
00095
00096 def gen_tags(self, tags):
00097 for key in tags.keys():
00098 s = StringIO.StringIO()
00099 t = ezt.Template(compress_whitespace = 0)
00100 t.parse(tags[key])
00101 t.generate(s, self.data)
00102 tags[key] = s.getvalue()
00103 return
00104
00105 def gen(self, fname, temp_txt, data, tags):
00106 f, lines = self.check_overwrite(fname)
00107 if not f:
00108 return
00109
00110 if not lines:
00111 s = StringIO.StringIO()
00112 t = ezt.Template(compress_whitespace = 0)
00113 t.parse(temp_txt)
00114 t.generate(s, data)
00115 taged_txt = s.getvalue().splitlines()
00116 else:
00117 taged_txt = lines
00118
00119
00120 gen_txt = self.replace_tags(taged_txt, tags)
00121 f.write(gen_txt)
00122 f.close()
00123 print " File \"" + fname + "\"" " was generated."
00124 return
00125
00126
00127
00128 if __name__ == "__main__":
00129 hoge = """
00130 protected:
00131 // <rtc-template block="inport_declar">
00132 // </rtc-template>
00133
00134 // <rtc-template block="outport_declar">
00135 // </rtc-template>
00136 """
00137 data = {"inport_declar": " hoge;\n dara;\n munya;",
00138 "outport_declar": " 1;\n 2;\n 3;"}
00139 g = gen_base()
00140 print g.replace_tags(hoge.splitlines(), data)