1 #!/usr/bin/ python
2 #-*- coding:utf-8 -*-
3 #操作同路径下的所有.cs .lua文件,并生成自动生成该cs文件的代码
4 importos5 globalclassCount,lastClassName6
7 defMachiningSourceCode(x):8 globalclassCount,lastClassName9 if x.find('class') >=0:10 #类名由tool方法参数决定
11 classCount = classCount + 1
12 xarr =x.split()13 nindex = -1
14 for a inrange(len(xarr)):15 if xarr[a] == 'class':16 nindex =a17 break
18 lastClassName = xarr[nindex + 1]19 xarr[nindex + 1] = '{0}'
20 x = ' '.join(xarr)21 x = 'stringBuilder.AppendFormat(\"'+x.strip('\n').replace('\"','\\"')+'\\n\",className%d);\n' %classCount22 elif x.find(lastClassName) >=0:23 #处理构造函数类名也由tool方法参数决定
24 x = x.replace(lastClassName,'{0}')25 x = 'stringBuilder.AppendFormat(\"'+x.strip('\n').replace('\"','\\"')+'\\n\",className%d);\n' %classCount26 else:27 x = 'stringBuilder.AppendLine(\"'+x.strip('\n').replace('\"','\\"')+'\");\n'
28 returnx29
30 #生成自动生成工具代码
31 defGenerateAutoCreatingToolCode(f,newfileName):32 lines =f.readlines()33 globalclassCount34 classCount =035 newlines =map(MachiningSourceCode,lines)36 toolFuncParam = ''
37 if classCount >0:38 for x inrange(classCount):39 toolFuncParam = toolFuncParam + ',string className%d' % (x + 1)40 namespaceReference = 'using UnityEngine;\nusing System.Text;\nusing System.IO;\n\n'
41 classAndFunc = 'public static class %s\n {\n public static void CreateClass(string stSaveFilePath %s,string stNameSpace = "")\n {\n \42 if (string.IsNullOrEmpty(stSaveFilePath))\n {\n return;\n }\n \43 StringBuilder stringBuilder = new StringBuilder();\n' %(newfileName,toolFuncParam)44 nameSpace = 'if (!string.IsNullOrEmpty(stNameSpace))\n {\n stringBuilder.AppendFormat\45 (string.Format(\"namespace {0}\\n\", stNameSpace));\n stringBuilder.AppendLine(\"{\");\n }\n'
46 saveFile = 'if (!string.IsNullOrEmpty(stNameSpace))\n {\n stringBuilder.AppendLine(\"}\");\n }\n \47 File.WriteAllText(stSaveFilePath, stringBuilder.ToString());\n }\n}'
48 newlines.insert(0,namespaceReference)49 newlines.insert(1,classAndFunc)50 newlines.insert(2,nameSpace)51 newlines.insert(len(newlines),saveFile)52 returnnewlines53
54 if __name__ == '__main__':55 try:56 globallastClassName57 lastClassName = 'lastClassName'
58
59 #创建生成代码文件夹
60 currentPath = os.path.abspath('.')61 createFilePath = os.path.join(currentPath,'createFile')62 if notos.path.exists(createFilePath):63 os.mkdir(createFilePath)64
65 for x in os.listdir("."):66 if os.path.isfile(x) and (os.path.splitext(x)[1] == '.cs' or os.path.splitext(x)[1] == '.lua'):67 readFilePath =os.path.join(currentPath,x)68 newfileName = 'Create%sAuto' %os.path.splitext(x)[0]69 newfile = newfileName + os.path.splitext(x)[1]70 writeFilePath =os.path.join(createFilePath,newfile)71 with open(readFilePath,'r') as f:72 newlines =GenerateAutoCreatingToolCode(f,newfileName)73
74 #生成代码文件
75 ifos.path.exists(writeFilePath):76 os.remove(writeFilePath)77 print('delete old file:%s' %writeFilePath)78 with open(writeFilePath,'w') as fw:79 fw.writelines(newlines)80 exceptException as e:81 print(e)82 n =input()83