168 lines
4.8 KiB
Python

#coding=utf-8
import sys,os,re,getopt,csv
repattern = re.compile(r'.*[\.]{1}([^\.]+)')
savepath = './'
def saveFile(filename, data):
file = open(filename, 'w', encoding='utf-8')
if file:
file.write(data)
file.close()
def convertName(name):
up = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890'
tempname = ''
if len(name) > 0:
tempname = name[0].upper()
for i in range(1,len(name)):
if name[i] not in up:
continue
tempname += name[i]
return tempname
def analysisCsv(filename, csvConfig, defConfig, loadConfig, csvNameListConfig):
namestr = os.path.split(filename)
if len(namestr) < 2:
print('err')
return
stname = os.path.splitext(namestr[1])[0]
convertname = convertName(stname)
#print('name:', name)
outText = '\n\nvar ' + convertname + 'Loader map[int32]*' + convertname
defText = ''
csvNameText = ''
firstAttrName = '' #第一个字段名称
with open(filename, 'r', encoding='utf-8') as myfile:
outText += '\ntype ' + convertname + ' struct{'
lines = csv.reader(myfile)
descList = []
typeList = []
nameList = []
index = 0
for line in lines:
if index == 0:
for i in range(0, len(line)):
descList.append(line[i].strip())
elif index == 1:
for i in range(0, len(line)):
nameList.append(line[i].strip())
elif index == 2:
for i in range(0, len(line)):
if line[i] == 'float':
typeList.append('float32')
elif line[i] == 'int':
typeList.append('int32')
elif line[i] == 'list':
typeList.append('[]string')
else:
typeList.append(line[i].strip())
else:
break
index += 1
#描述
if len(descList) != len(typeList) or len(descList) != len(nameList):
print('err:',stname)
return
for i in range(0,len(descList)):
_desc = descList[i]
_type = typeList[i]
_name = nameList[i]
outText += '\n\t' + convertName(_name) + '\t' + _type + '\t`csv:"' + _name + '"`\t\t//' + _desc
if firstAttrName == '':
firstAttrName = convertName(_name)
outText += '\n}'
outText += '\nfunc ' + convertname + 'Load(path string) {\n\tcfg := []*' + convertname + '{}\n'
outText += '\t' + convertname + 'Loader = map[int32]*' + convertname + '{}\n'
outText += '\tloadCsvCfg(path + "' + stname + '.csv", &cfg)\n\tfor _,row := range cfg{\n\t\t'
outText += convertname + 'Loader[row.' + firstAttrName + '] = row\n\t}\n}'
defText = '\n\tCFG_' + convertname + ' = "' + stname + '.csv"'
csvNameText = '\n\tCFGNameList["' + stname + '"] = ' + stname + 'Load'
loadConfig.append('\n\t'+convertname+"Load(path)")
print('file done:',filename)
csvConfig.append(outText)
defConfig.append(defText)
csvNameListConfig.append(csvNameText)
#saveFile(savepath + stname+'.go', outText)
def analysisXml(filename, defConfig):
print('xml:',filename)
namestr = os.path.split(filename)
if len(namestr) < 2:
print('err')
return
stname = os.path.splitext(namestr[1])[0]
convertname = convertName(stname)
defText = '\n\t"' + stname + '",'
defConfig.append(defText)
#获取路径下的指定类型文件列表
def getFileList(path, fileList):
for parent, dirnames, filenames in os.walk(path):
for filename in filenames:
match = repattern.match(filename)
if match:
filetype = match.groups()[0]
if filetype in ['csv']:
fileList.append(os.path.join(parent, filename))
if filetype in ['xml']:
fileList.append(os.path.join(parent, filename))
if __name__ == '__main__':
configFile = ''#'D:/rowok/cehua/'
try:
opts,args = getopt.getopt(sys.argv[1:], "hp:d:", ["help","dir="])
for opt, arg in opts:
if opt in ("-d", "--dir"):
configFile = arg
except getopt.GetoptError:
useage()
sys.exit(1)
csvConfigFile = configFile + '/csv'
xmlConfigFile = configFile + '/xml'
#解析csv文件获得服务器使用的结构体
fileList = []
csvConfig = []
defConfig = []
csvNameListConfig = []
loadConfig = []
xmlConfigFileList = []
defXmlConfig = []
getFileList(csvConfigFile, fileList)
getFileList(xmlConfigFile, xmlConfigFileList)
for file in fileList:
analysisCsv(file, csvConfig, defConfig, loadConfig, csvNameListConfig)
for file in xmlConfigFileList:
analysisXml(file, defXmlConfig)
file = open(savepath+'config_csv.go', 'w', encoding='utf-8')
if file:
file.write('package serverproto\n\n')
file.write('const (')
for out in defConfig:
file.write(out)
file.write('\n)\n')
file.write('var CFGNameList = map[string]func(path string){}')
file.write('\n\nfunc configNameListInit(){')
for out in csvNameListConfig:
file.write(out)
file.write('\n}')
file.write('\n\n\nvar XmlFileList = []string{')
for out in defXmlConfig:
file.write(out)
file.write('\n}\n\n')
file.write('//load config data\nfunc ConfigInit(path string) {')
file.write('\n\tconfigNameListInit()')
for out in loadConfig:
file.write(out)
file.write('\n}')
for out in csvConfig:
file.write(out)
file.close()