配置文件config.json
[
{
"key" : "jiebabuyuxiniubuyu",
"add_func_num" :1,
"lua_in_path":"../../../..",
"lua_out_path":"../../../../scirptdecode",
"lua_get_dir_path" : "/Users/li/mypro/xfront/Resources",
"lua_born_path" : "../../../../scirptdecode/main/game",
"cplus_get_dir_path":"/Users/li/mypro/xfront/Resources",
"cplus_born_path":"../../../../XnFramework/cocos/quick-3.3/quick/lib/XnGameSrc",
"oc_in_path":"",
"oc_out_path":"",
"client_config":"../../../../scirptdecode/main/res/client_config",
"config_list":{
"UnionID": 101,
"ChildUnionID": 1143,
"KindID": 404,
"ChannelID": 0,
"AppID": "80252127002"
},
"wxAppID":"wxacfcf61a237d3658",
"version":"2.15",
"functionOpen":{
"isaddfunc":"True",
"isaddfile":"True",
"isadddesc":"True",
"isaddfile_lua":"True"
}
}
]
python文件autoBornCode.py
#! /usr/bin/python
# -*- coding: UTF-8 -*-
# author : liqiang
# desc : 自动生成辣鸡代码
# 逻辑重理
# 此脚本功能有
# 1.生成文件(lua,c++)
# 2.混入方法(lua)
# 3.混入注释(lua,oc,c++)
# 4.修改打包配置
import os,sys
import random
import string
import re
import md5
import time
import json
import shutil
import subprocess #调用命令方法
import hashlib
import time
from os.path import join, getsize
s = os.sep #多平台 路径分割符号是'\',在Linux上是‘/’
# 模拟生成文件目录的源目录
cplus_get_dir_path = '/Users/li/mypro/xfront/Resources'
lua_get_dir_path = '/Users/li/mypro/xfront/Resources'
cplus_born_path = '../../../../XnFramework/cocos/quick-3.3/quick/lib/XnGameSrc'
lua_born_path = '../../../../scirptdecode/main/game'
copyfilelist = ['luaFramework','main','package/BuYu/res','package/BuYu/src']
# 生成单个c++文件内的方法数量
cplusFuncConut = 1
context = {
'key' : 'xiniu',
'add_func_num' : 10,
'lua_in_path' : '../../../..',
'lua_out_path' : '../../../../scirptdecode',
'lua_get_dir_path':lua_get_dir_path,
'lua_born_path':lua_born_path,
'cplus_get_dir_path':cplus_get_dir_path,
'cplus_born_path':cplus_born_path,
'oc_in_path':'',
'oc_out_path':'./',
'isaddfunc':True, #加混淆开关
'isaddfile':True, #加文件开关
'isadddesc':True, #加注释开关 c++添加没有用 会被过滤掉
'isaddfile_lua':True,
'wxAppID':"wxacfcf61a237d3658",
'version':'2.15',
'config_list':{
"UnionID": 101,
"ChildUnionID": 1143,
"KindID": 404,
"ChannelID": 0,
"AppID": "80252127002"
}
}
add_file_count = 0
add_function_count = 0
add_desc_count = 0
# 配置文件解释
# "key" : "jiebabuyuxiniubuyu",
# "add_func_num" :10,
# "lua_in_path":"../../../../scirptdecode/main/res/client_config",
# "lua_out_path":"../../../../scirptdecode",
# "config_list":{
# "UnionID": 101,
# "ChildUnionID": 1143,
# "KindID": 404,
# "ChannelID": 0,
# "AppID": "80252127002"
# },
# "wxAppID":"wxacfcf61a237d3658",
# "version":"2.15",
#----------------------------------------------------通用模块------------------------------------------------
class ProgressBar: # 终端进度条
def __init__(self, count = 0, total = 0, width = 50):
self.count = count
self.total = total
self.width = width
def move(self):
self.count += 1
return self.count
def log(self, s = ""): #显示进度
sys.stdout.write(' ' * (self.width + 9) + '\r')
sys.stdout.flush()
# print s
progress = self.width * self.count / self.total
sys.stdout.write('{0:3}/{1:3}: '.format(self.count, self.total))
sys.stdout.write('#' * progress + '-' * (self.width - progress) + '\r')
if progress == self.width:
sys.stdout.write('\n')
sys.stdout.flush()
# 判断文件是否存在key r
def StrIsInFile(filepath,r):
fp =open(filepath,'r+')
# print name
for line in fp.readlines():
if r in line:
return True
fp.close()
return False
# 得到一个md5加密名字
def getOneName(filename):
# 随机方法
# num = random.randint(10, 20)
# random.uniform
# random.randint
# random.randrange(0, 101, 2)
# random.choice('abcdefg&#%^*f')
# random.sample('abcdefghij',3)
# m1 = md5.new()
m1 = hashlib.md5()
m1.update(context['key']+filename.split(s)[-1]) #更新一次 改变一次 filename格式为 文件名 + 方法行号 + 方法当前方法行数
# print filename.split("/")[-1]
text = m1.hexdigest()
text = text[0:7]
# return string.join(random.sample(m1.hexdigest(),random.randint(4,10)),"")
# print text,context['key']+filename.split(s)[-1]
return str(text)
# names[asciis] = chr(asciis)
# 得到字段头 为了好查找 暂时先只加一个
def getHeadName():
return random.choice ( ['get'])
#----------------------------------------------------通用模块end------------------------------------------------
#----------------------------------------------------生成文件信息模块start------------------------------------------------
# 生成一个图形注释 适用于.h .cpp .mm .m .hpp
def addDescimg():
text = [
'\n/** 佛祖保佑必过包',
'\n* .,:,,, .::,,,::. 佛祖保佑必过包',
'\n* .::::,,;;, .,;;:,,....:i: 佛祖保佑必过包',
'\n* :i,.::::,;i:. ....,,:::::::::,.... .;i:,. ......;i. 佛祖保佑必过包',
'\n* :;..:::;::::i;,,:::;:,,,,,,,,,,..,.,,:::iri:. .,:irsr:,.;i. 佛祖保佑必过包',
'\n* ;;..,::::;;;;ri,,,. ..,,:;s1s1ssrr;,.;r, 佛祖保佑必过包',
'\n* :;. ,::;ii;:, . ................... .;iirri;;;,,;i, 佛祖保佑必过包',
'\n* ,i. .;ri:. ... ............................ .,,:;:,,,;i: 佛祖保佑必过包',
'\n* :s,.;r:... ....................................... .::;::s; 佛祖保佑必过包',
'\n* ,1r::. .............,,,.,,:,,........................,;iir; 佛祖保佑必过包',
'\n* ,s;........... ..::.,;:,,. ...............,;1s 佛祖保佑必过包',
'\n* :i,..,. .,:,,::,. .......... .......;1, 佛祖保佑必过包',
'\n* ir,....:rrssr;:, ,,.,::. .r5S9989398G95hr;. ....,.:s, 佛祖保佑必过包',
'\n* ;r,..,s9855513XHAG3i .,,,,,,,. ,S931,.,,.;s;s&BHHA8s.,..,..:r: 佛祖保佑必过包',
'\n* :r;..rGGh, :SAG;;G@BS:.,,,,,,,,,.r83: hHH1sXMBHHHM3..,,,,.ir. 佛祖保佑必过包',
'\n* ,si,.1GS, sBMAAX&MBMB5,,,,,,:,,.:&8 3@HXHBMBHBBH#X,.,,,,,,rr 佛祖保佑必过包',
'\n* ;1:,,SH: .A@&&B#&8H#BS,,,,,,,,,.,5XS, 3@MHABM&59M#As..,,,,:,is, 佛祖保佑必过包',
'\n* .rr,,,;9&1 hBHHBB&8AMGr,,,,,,,,,,,:h&&9s; r9&BMHBHMB9: . .,,,,;ri. 佛祖保佑必过包',
'\n* :1:....:5&XSi;r8BMBHHA9r:,......,,,,:ii19GG88899XHHH&GSr. ...,:rs. 佛祖保佑必过包',
'\n* ;s. .:sS8G8GG889hi. ....,,:;:,.:irssrriii:,. ...,,i1, 佛祖保佑必过包',
'\n* ;1, ..,....,,isssi;, .,,. ....,.i1, 佛祖保佑必过包',
'\n* ;h: i9HHBMBBHAX9: . ...,,,rs, 佛祖保佑必过包',
'\n* ,1i.. :A#MBBBBMHB##s ....,,,;si. 佛祖保佑必过包',
'\n* .r1,.. ,..;3BMBBBHBB#Bh. .. ....,,,,,i1; 佛祖保佑必过包',
'\n* :h;.. .,..;,1XBMMMMBXs,.,, .. :: ,. ....,,,,,,ss. 佛祖保佑必过包',
'\n* ih: .. .;;;, ;;:s58A3i,.. ,. ,.:,,. ...,,,,,:,s1, 佛祖保佑必过包',
'\n* .s1,.... .,;sh, ,iSAXs;. ,. ,,.i85 ...,,,,,,:i1; 佛祖保佑必过包',
'\n* .rh: ... rXG9XBBM#M#MHAX3hss13&&HHXr .....,,,,,,,ih; 佛祖保佑必过包',
'\n* .s5: ..... i598X&&A&AAAAAA&XG851r: ........,,,,:,,sh; 佛祖保佑必过包',
'\n* . ihr, ... . .. ........,,,,,;11:. 佛祖保佑必过包',
'\n* ,s1i. ... ..,,,..,,,.,,.,,.,.. ........,,.,,.;s5i. 佛祖保佑必过包',
'\n* .:s1r,...................... ..............;shs, 佛祖保佑必过包',
'\n* . .:shr:. .... ..............,ishs. 佛祖保佑必过包',
'\n* .,issr;,... ...........................,is1s;. 佛祖保佑必过包',
'\n* .,is1si;:,....................,:;ir1sr;, 佛祖保佑必过包',
'\n* ..:isssssrrii;::::::;;iirsssssr;:.. 佛祖保佑必过包',
'\n* .,::iiirsssssssssrri;;:. 佛祖保佑必过包',
'\n*/ //佛祖保佑必过包\n//佛祖保佑必过包\n//佛祖保佑必过包'
]
return text
# 自动生成oc.h文件
def autoTexth(filename):
global add_file_count
add_file_count = add_file_count + 1
text = ['// '+filename+'.h\n',
'// '+filename+'\n',
'// \n',
'// Created By liqiang on 2017/8/16.\n',
'// Copyright (c) 2013 maple. All rights reserved.\n',
'// \n',
'\n',
'#import <Foundation/Foundation.h>\n',
' @interface '+filename+' : NSObject\n',
' + (NSString*)UDID;\n',
' @end\n'
]
return text
# 自动生成oc.m文件
def autoTextM(filename):
global add_file_count
add_file_count = add_file_count + 1
text = [
'// '+filename+'.m\n',
'// xiniu\n',
'// \n',
'// Created by liqiang on 2017/8/16.\n',
'// Copyright © 2017年 Li. All rights reserved.\n'
'//\n',
'\n',
'#import \"'+filename+'.h\"\n',
'@implementation '+filename+'\n',
'\n',
'+ (NSString*)UDID\n',
'{\n',
' NSString *udid = @\"'+str(random.randint(10000,10000000))+'\";\n',
' return udid;\n',
'}\n',
'@end//\n'
]
return text
# 生成一个c++方法 加上获取当前不定的时间 防止被编译器过滤
def autoTextCpluscpp(filename,fn):
functionname0 = 'xn' + getOneName(filename+'0')
functionname1 = 'xn' + getOneName(filename+'1')
functionname2 = 'xn' + getOneName(filename+'2')
functionname3 = 'xn' + getOneName(filename+'3')
functionname5 = 'xn' + getOneName(filename+'4')
functionname4 = getHeadName()+getOneName(filename+'4')
text = [
'bool GetIs'+filename+'(){\n',
' int '+functionname1 + '=' + '12312312'+';\n',
' int '+functionname2 + '=' + '45645645'+';\n',
' int '+functionname3+'='+functionname1+'+'+functionname2+';\n',
' bool '+functionname5+' = '+functionname3+'> 0; \n',
' time_t tt = time(NULL);\n\n',
' tm* t = localtime(&tt);\n\n',
' bool Is'+filename+' = false;\n',
' if (t->tm_year > 0){\n',
' Is'+filename+' = true;\n\n',
' }\n',
' return Is'+filename+' and '+functionname5+';\n\n',
'}\n'
]
return text
# 生成一个C++ extern 声明
def autoTextCplusH(filename,fn):
text = [
' extern bool GetIs'+filename+'();\n\n'
]
return text
# 添加lua 辣鸡方法
def autoTextLua(filename):
# print filename+'1\n'
global add_function_count
add_function_count = add_function_count + 1
functionname1 = 'xn' + getOneName(filename+'1')
functionname2 = 'xn' + getOneName(filename+'2')
functionname3 = 'xn' + getOneName(filename+'3')
functionname4 = getHeadName()+getOneName(filename+'4')
text = [
'\nlocal function '+functionname4+'()\n',
' local '+functionname1 + '=' + '123'+'\n',
' local '+functionname2 + '=' + '456'+'\n',
' local '+functionname3+'='+functionname1+'+'+functionname2+'\n',
' return '+functionname3+'\n',
'end\n\n'
]
# print string.join(text)
return string.join(text)
# 添加lua 辣鸡文件context
def autoTextLuafile(filename,fn):
# print filename+'1\n'
global add_file_count
add_file_count = add_file_count + 1
functionname0 = 'xn' + getOneName(filename+'0')
functionname1 = 'xn' + getOneName(filename+'1')
functionname2 = 'xn' + getOneName(filename+'2')
functionname3 = 'xn' + getOneName(filename+'3')
functionname4 = getHeadName()+getOneName(filename+'4')
text = [
'local ' + functionname0 + ' = {}\n',
'\nlocal function '+functionname4+'()\n',
' local '+functionname1 + '=' + '123'+'\n',
' local '+functionname2 + '=' + '456'+'\n',
' local '+functionname3+'='+functionname1+'+'+functionname2+'\n',
' return '+functionname3+'\n',
'end\n\n',
'return ' + functionname0 + '\n'
]
# print string.join(text)
return string.join(text)
# 生成OC文件
def addOneOcFile(filenumber):
#生成文件名
filename = 'test' + getOneName(filenumber)
functionname = random.choice ( ['get', 'set', 'xiniu', 'xn', 'BuYu','cc','ccb','ccui'])+filename
#生成m文件
# os.mknod(filename+".m")
fp = open(context['oc_out_path'] + s+filename+".m",'w')
#生成m文件的内容 并写入
text = autoTextM(filename)
for item in text:
fp.write(item)
# out.write(i)
fp.close()
#生成h文件
# os.mknod(filename+".h")
if os.path.exists(context['oc_out_path']) :
shutil.rmtree(context['oc_out_path'])
os.mkdir(context['oc_out_path'])
fp = open(context['oc_out_path'] + s+filename+".h",'w')
#生成h文件内容并写入
text = autoTexth(filename)
for item in text:
fp.write(item)
fp.close()
#----------------------------------------------------生成文件信息模块end------------------------------------------------
#----------------------------------------------------增加方法信息模块start------------------------------------------------
# 获取文件列表
def getCodeList(filePaths,strs):
filelist = [] #所有res列表
for filepath in filePaths:
for dirpath,dirname,filename in os.walk(filepath):
for fn in filename:
# print fn
try:
name =dirpath + s + fn
# isadd = False
# for value in strs: #允许文件
# if value in fn:
# # print value
# isadd = True
# if isadd:
filelist.append(name)
except:
print "File'" + name + "'can't be read"
return filelist
# 替换字符方法
def string_switch(x,y,z,type,ss=1):
with open(x, "r") as f:
#readlines以列表的形式将文件读出
lines = f.readlines()
# ss = 'g'
with open(x, "w") as f_w:
#定义一个数字,用来记录在读取文件时在列表中的位置
n = 0
#默认选项,只替换第一次匹配到的行中的字符串
# print addDesc(x+str(n))+z,y
if ss :
for line in lines:
if line.startswith(y):
# if line.startswith(':'):
if type == 1 :
if ":" in line:
line = line.replace(y,autoTextLua(x+str(n))+z)
# print autoTextLua(x+str(n))+z
n += 1
else:
# print addDesc(x,str(n))+z,y + ' 1'
line = line.replace(y,addDesc(x,str(n))+z)
# print x,n
n += 1
if ss == n :
break
f_w.write(line)
n += 1
#将剩余的文本内容继续输出
for i in range(n,len(lines)):
f_w.write(lines[i])
#全局匹配替换
elif ss == 'g':
for line in lines:
if y in line:
line = line.replace(y,autoTextLua(x+str(n))+z)
f_w.write(line)
# 混淆lua文件
def updateLuaFile():
print 'updateLuaFile'
_copyfilelist = copyfilelist
#删除文件夹
if os.path.exists(context['lua_out_path']) :
shutil.rmtree(context['lua_out_path'])
for item in _copyfilelist:
print context['lua_in_path']+s+item + ' copy to',
print context['lua_out_path']+s+item
if os.path.exists(context['lua_out_path']+s+item) :
shutil.rmtree(context['lua_out_path']+s+item)
#移动文件夹
shutil.copytree(context['lua_in_path']+s+item,context['lua_out_path']+s+item)
if context['isaddfunc']:
codelist = getCodeList([context['lua_out_path']+s+item],'')
#初始化进度条
bar = ProgressBar(total = len(codelist))
totalnum = len(codelist)
# print totalnum
for c in codelist:
bar.move()
bar.log()
# StrIsInFile(c,'function')
# for item in range(context['add_func_num']):
if '.git' != c.split(c)[-1]:
if '.gitignore' != c.split(c)[-1]:
for item in range(context['add_func_num']):
# print c
if c.endswith('.lua'):
string_switch(c,'function ','\nfunction ',1,1)
# print codelist
def updataFuncFile():
updateLuaFile()
#----------------------------------------------------增加方法信息模块end------------------------------------------------
#----------------------------------------------------增加注释信息模块start------------------------------------------------
def addDesctxt(files,st):
filename = files.split(s)[-1]
m1 = md5.new()
m1.update(context['key']+filename.split(s)[-1])
# print filename.split("/")[-1]
text = st + m1.hexdigest()
return text
def addDesc(filen,n):
if filen.endswith('.lua') :
if filen.endswith('.lua') :
return addDesctxt(filen+n,'--')
elif filen.endswith('.cpp') or filen.endswith('.c') or filen.endswith('.m') or filen.endswith('.mm') or filen.endswith('.hpp') :
# print addDesctxt(filen+n,'//')
return addDesctxt(filen+n,'//')
return ''
#删除文件夹
if os.path.exists(out_filepath) :
shutil.rmtree(out_filepath)
#移动文件夹
shutil.copytree(in_filepath,out_filepath)
codelist = getCodeList([out_filepath],'')
#初始化进度条
bar = ProgressBar(total = len(codelist))
totalnum = len(codelist)
# print totalnum
for c in codelist:
bar.move()
bar.log()
# StrIsInFile(c,'function')
# for item in range(context['add_func_num']):
if '.git' != c.split(s)[-1]:
if '.gitignore' != c.split(s)[-1]:
for item in range(context['add_func_num']):
if c.endswith('.lua') :
string_switch(c,'function ','\nfunction ',2,1)
elif c.endswith('.cpp') or c.endswith('.c') or c.endswith('.hpp') :
string_switch(c,'#include ','\n#include ',2,1)
elif c.endswith('.m'):
string_switch(c,'@interface ','\n@interface ',2,1)
elif c.endswith('.h') or c.endswith('.mm'):
string_switch(c,'#include ','\n#include ',2,1)
string_switch(c,'@interface ','\n@interface ',2,1)
#----------------------------------------------------更新保持使用过的key------------------------------------------------
def updatekey():
print 'cur key '+context['key']
fp = open('keycode.txt','a')
fp.write(context['key'] + ' ' + time.asctime( time.localtime(time.time()) ) + '\n')
fp.close()
# print 'new key'
#----------------------------------------------------读取配置------------------------------------------------
def load():
with open('config.json') as json_file:
data = json.load(json_file)
return data
def getConfig(lenth):
jsonstr = load()[lenth]
# print jsonstr
config = json.dumps(jsonstr)
# key1
if jsonstr["key"]:
context['key'] = jsonstr["key"]
# 添加数量8
if jsonstr["add_func_num"]:
context['add_func_num'] = jsonstr["add_func_num"]
# lua混淆文件路径
if jsonstr["lua_in_path"]:
context['lua_in_path'] = jsonstr["lua_in_path"]
if jsonstr["lua_out_path"]:
context['lua_out_path'] = jsonstr["lua_out_path"]
# lua 生成文件路径
if jsonstr["lua_get_dir_path"]:
context['lua_get_dir_path'] = jsonstr["lua_get_dir_path"]
if jsonstr["lua_born_path"]:
context['lua_born_path'] = jsonstr["lua_born_path"]
#c++ 生成文件路径
if jsonstr["cplus_get_dir_path"]:
context['cplus_get_dir_path'] = jsonstr["cplus_get_dir_path"]
if jsonstr["cplus_born_path"]:
context['cplus_born_path'] = jsonstr["cplus_born_path"]
# oc path config6
if jsonstr["oc_in_path"]:
context['oc_in_path'] = jsonstr["oc_in_path"]
if jsonstr["oc_out_path"]:
context['oc_out_path'] = jsonstr["oc_out_path"]
if jsonstr["client_config"]:
context['client_config'] = jsonstr["client_config"]
# 修改配置
if jsonstr["config_list"]:
context['config_list'] = jsonstr["config_list"]
if jsonstr["wxAppID"] :
context['wxAppID'] = jsonstr["wxAppID"]
if jsonstr["version"]:
context['version'] = jsonstr["version"]
if jsonstr["functionOpen"] :
cfg = jsonstr["functionOpen"]
# for t in cfg:
# print t,cfg[t]
# pass
# if jsonstr["isaddfunc"]:
context['isaddfunc'] = cfg["isaddfunc"]
# if jsonstr["isaddfile"]:
context['isaddfile'] = cfg["isaddfile"]
# if jsonstr["isadddesc"]:
context['isadddesc'] = cfg["isadddesc"]
# if jsonstr["isaddfile_lua"]:
context['isaddfile_lua'] = cfg["isaddfile_lua"]
def getWord2(filepath,word1,value):
fp =open(filepath,'r')
# print name
oldline = ''
newline = ''
for line in fp.readlines():
if not s in line:
if word1 in line:
oldline = line
if '\"AppID' == word1:
newline = " "+word1+"\""+" : "+str(value) + "\n"
else:
newline = " "+word1+"\""+" : "+str(value) + ",\n"
fp.close()
return [oldline,newline]
def getWord3(filepath,word1,value):
fp =open(filepath,'r')
# print name
oldline = ''
newline = ''
ischange = False
for line in fp.readlines():
oldline = line
if ischange :
newline = word1+" : \""+str(value) + "\",\n"
ischange = False
if word1 in line:
ischange = True
fp.close()
return [oldline,newline]
def getWord4(filepath,word1,value):
fp =open(filepath,'r')
# print name
oldline = ''
newline = ''
for line in fp.readlines():
if not s in line:
if word1 in line:
oldline = line
if 'wx' in line:
newline = word1+"."+str(value) + "\n"
fp.close()
return [oldline,newline]
def replace(file_path, old_str, new_str,isbreak):
try:
f = open(file_path,'r+')
all_lines = f.readlines()
f.seek(0)
f.truncate()
for line in all_lines:
line = line.replace(old_str, new_str)
f.write(line)
if isbreak :
break
f.close()
except Exception,e:
print e
def change_config():
# codelist = getCodeList(context['lua_in_path'],'')
configpath = context['client_config']+'/Config.lua'
# print configpath
# print context['config_list']
# 设置参数
for item in context['config_list']:
# print item
# print context['config_list'][item]
str12 = getWord2(configpath,"\""+item,context['config_list'][item])
# print str12[0]
# print str12[1]
if str12[0]:
replace(configpath,str12[0],str12[1],False)
# 设置微信appid
# wxconfig = context['lua_in_path']+'/SDK.lua'
# str2 = getWord3(wxconfig,"\""+'"Weixin"',context['wxAppID'])
# if str2[0]:
# replace(wxconfig,str2[0],str2[1],True)
# print context['wxAppID']
# print str2[0]
# print str2[1]
# versionconfig = context['lua_in_path'] + '/Version.lua'
# str2 = getWord4(versionconfig,'101',context['version'])
# if str2[0]:
# replace(wxconfig,str2[0],str2[1])
# versionconfig2 = context['lua_out_path'] + '/package/BuYu/res/client_config/Version.lua'
# str2 = getWord4(versionconfig,'101',context['version2'])
# if str2[0]:
# replace(wxconfig,str2[0],str2[1])
# pt = open(configpath,'w')
#----------------------------------------------------File------------------------------------------------
# 深度混淆
# [[
# 1.仿照一个app目录
# 2.生成文件
# 3.假调用
# ]]
def addCplusFile(filenumber,path,fun_num):
global add_file_count
add_file_count = add_file_count + 2
#生成文件名
filename = 'XnGane' + getOneName(filenumber)
#生成cpp文件
# os.mknod(path+".cpp")
fp = open(path+".cpp",'w')
#生成m文件的内容 并写入
text = addDescimg()
for item in text:
fp.write(item)
texth = [
'//\n',
'// '+filename+'.hpp\n',
'// xiniu\n',
'//\n',
'// Created by liqiang on 2017/8/17.\n',
'//\n',
'//\n\n\n',
'#include <time.h>\n',
'#include \"'+path.split('/')[-1]+'.hpp\"\n\n'
]
txt = [
'bool GetIs'+filename+'(){\n'
]
txtis = 'return'
for item in texth:
fp.write(item)
for _fun_num in range(fun_num):
# print _fun_num
if int(_fun_num) == 0 :
txtis = txtis + ' GetIs'+filename+str(_fun_num)+'()'
else:
txtis = txtis + (' and GetIs'+filename+str(_fun_num))+'()'
text = autoTextCpluscpp(filename+str(_fun_num),path.split('/')[-1])
for item in text:
fp.write(item)
txtis = txtis +';\n'
txt.append(txtis)
txt.append('}\n')
# 加主方法
for item in txt:
fp.write(item)
# out.write(i)
fp.close()
#生成h文件
# os.mknod(path+".hpp")
fp = open(path+".hpp",'w')
#生成h文件内容并写入
text = addDescimg()
for item in text:
fp.write(item)
texth = [
'//\n',
'// '+path.split('/')[-1]+'.hpp\n',
'// xiniu\n',
'//',
'// Created by liqiang on 2017/8/17.\n',
'//\n',
'//\n\n',
'#ifndef '+path.split('/')[-1]+'_hpp\n',
'#define '+path.split('/')[-1]+'_hpp\n\n\n\n',
'#include <stdio.h>\n\n'
]
for item in texth:
fp.write(item)
# for _fun_num in range(fun_num):
text = autoTextCplusH(filename,path.split('/')[-1])
for item in text:
fp.write(item)
fp.write('#endif /* '+path.split('/')[-1]+'_hpp */\n\n')
fp.close()
return filename
def addluaFile(filenumber,path):
#生成文件名
filename = 'XnGane' + getOneName(filenumber)
#生成cpp文件
# os.mknod(path+".cpp")
# print path + '.lua'
fp = open(path+".lua",'w')
#生成m文件的内容 并写入
text = autoTextLuafile(filename,path.split('/')[-1])
for item in text:
fp.write(item)
# out.write(i)
fp.close()
return filename
def getdirsize(d):
size = 0L
for root, dirs, files in os.walk(d):
size += sum([getsize(join(root, name)) for name in files])
if size/1024.0/1024.0 > 1 :
return str(size/1024.0/1024.0)[0:5] + 'MB'
else:
return str(size/1024.0)[0:5] + 'KB'
def getDirlistcplus():
fun_num = cplusFuncConut
# 模拟在c++实现当前lua代码
lua_path = context['cplus_get_dir_path']
# print lua_path
out_path = context['cplus_born_path']
lualist = getCodeList([lua_path],'')
# print len(lualist)
if os.path.exists(out_path) :
shutil.rmtree(out_path)
os.mkdir(out_path)
addfilenum = 0
bar = ProgressBar(total = len(lualist))
isone = True
bornfillist = []
funclist = []
for item in lualist:
bar.move()
bar.log()
# 获得lua文件路径得到文件名 以xfront/Resources 分割
# print '1'
if isone :
isone = False
else:
# print item
subpath = (item.split(lua_path[-10:])[1]).split('.')[0]
if not 'game/' == subpath and (not 'config' in subpath) and (not '(' in subpath) and (not ')' in subpath)and (not 'map_num_t' in subpath) :
addfilenum = addfilenum + 1
path = subpath
isadd = True
for subitem in bornfillist:
if path.split('/')[-1] in subitem:
isadd = False
if isadd:
# print path
# print out_path +s+ path
sbpath = out_path+s + path
sbpathlt = sbpath.split('/')
sbpathlt.pop()
# print s.join(sbpathlt)
pathjoin = s.join(sbpathlt)
if not os.path.exists( s.join(sbpathlt)) :
sbpathlt.pop()
if not os.path.exists( s.join(sbpathlt)) :
pathjoin1 = s.join(sbpathlt)
os.mkdir( pathjoin1)
os.mkdir( pathjoin)
else:
# if
os.mkdir( pathjoin)
# for num in range(10):
num = ''
# print out_path+s + path+str(num)
curlist = path.split('/')
curlist.pop()
path = s.join(curlist) + '/Xn' + path.split('/')[-1]
if path[0] == '/':
path = path[1:len(path)]
funcname = addCplusFile(path + str(addfilenum)+str(num),out_path+s + path+str(num),fun_num)
# for
# for item in range(fun_num):
funclist.append(funcname)
bornfillist.append(path)
if not context['isaddfile'] and len(funclist) > 2:
break
#调用文件
fp = open(out_path+s+'gamerun.hpp','w')
fp.write('#ifndef GameRun_h\n#define GameRun_h\nextern bool mainCall();\n#endif')
fp.close()
fp = open(out_path+s+'gamerun.cpp','w')
fp.write('#include "gamerun.hpp"\n')
# del bornfillist[0]
# del funclist[0]
for item in bornfillist:
fp.write('#include "'+item+'.hpp"\n')
fp.write('bool mainCall()\n{\n')
isone = True
for item in funclist:
if isone :
isone = False
# fp.write(' if (GetIs'+item+'()){\n return;\n }\n\n')
fp.write(' bool is = GetIs'+item+'();\n')
else:
fp.write(' if (is){\n is = GetIs'+item+'();\n }\n\n')
# fp.write(' GetIs'+item+'();\n')
fp.write(' return is;\n}\n')
# print out_path + item.split('BuYu/src')[1].split('.')[0]+'.cpp'
# print out_path + item.split('BuYu/src')[1].split('.')[0]+'.hpp'
# print 'c++ file ' + str(len(bornfillist))
print 'c++辣鸡文件大小 ' + str(getdirsize(out_path))+' ' + str(out_path)
print 'c++辣鸡文件数量 ' + str(len(bornfillist)*2 + 2)
def getDirlistlua():
# 复制一个目录结构 换成辣鸡代码文件
lua_path = context['lua_get_dir_path']
# print lua_path
out_path = context['lua_born_path']
lualist = getCodeList([lua_path],'')
# print len(lualist)
if os.path.exists(out_path) :
shutil.rmtree(out_path)
os.mkdir(out_path)
addfilenum = 0
isone = True
bornfillist = []
funclist = []
bar = ProgressBar(total = len(lualist))
for item in lualist:
# 获得lua文件路径得到文件名 以xfront/Resources 分割
# print '1'
bar.move()
bar.log()
if isone :
isone = False
else:
# print item
subpath = (item.split(lua_path[-10:])[1]).split('.')[0]
if not 'game/' == subpath and (not 'config' in subpath) and (not '(' in subpath) and (not ')' in subpath)and (not 'map_num_t' in subpath) :
addfilenum = addfilenum + 1
path = subpath
isadd = True
for subitem in bornfillist:
if path.split('/')[-1] in subitem:
isadd = False
if isadd:
# print path
# print out_path +s+ path
sbpath = out_path+s + path
sbpathlt = sbpath.split('/')
sbpathlt.pop()
# print s.join(sbpathlt)
pathjoin = s.join(sbpathlt)
if not os.path.exists( s.join(sbpathlt)) :
sbpathlt.pop()
if not os.path.exists( s.join(sbpathlt)) :
pathjoin1 = s.join(sbpathlt)
os.mkdir( pathjoin1)
os.mkdir( pathjoin)
else:
# if
os.mkdir( pathjoin)
# for num in range(10):
num = ''
# print out_path+s + path+str(num)
curlist = path.split('/')
curlist.pop()
path = s.join(curlist) + '/Xn' + path.split('/')[-1]
if path[0] == '/':
path = path[1:len(path)]
funcname = addluaFile(path + str(addfilenum)+str(num),out_path+s + path+str(num))
# for
funclist.append(funcname)
bornfillist.append(path+str(num))
if not context['isaddfile'] and len(funclist) > 2:
break
# print 'lua file ' + str(len(bornfillist))
print 'lua辣鸡文件大小 ' + str(getdirsize(out_path))+' ' + str(out_path)
print 'lua辣鸡文件数量 ' + str(len(bornfillist) )
def DeepAutoCode():
print '生成目录'
# c++
if context['isaddfile'] :
getDirlistcplus()
# lua
if context['isaddfile_lua'] :
getDirlistlua()
print '生成文件'
# getCodeFile()
# print '调用文件'
#----------------------------------------------------main------------------------------------------------
def main():
# 1.生成文件(lua,c++)
# 2.混入方法(lua)
# 3.混入注释(lua,oc,c++)
# 4.修改打包配置
print '感谢使用'
# print os.getcwd()
# 获取配置
configlen = len(load())
# print configlen
if configlen > 0 :
getConfig(0)
# 更新key
updatekey()
# 更新文件 加方法 垃圾代码
updataFuncFile()
# 深度生成文件
DeepAutoCode()
# 替换Info
change_config()
global add_function_count
global add_file_count
print '总共增加方法' + str(add_function_count) + ' 个'
print '总共增加文件' + str(add_file_count) + ' 个'
if __name__ == "__main__":
main()