def refreshProjectJson(rootPath, modules, isCleanJSList, moduleType=None): if modules == None or len(modules) < 1: raise_known_error( "modules 参数错误,需要传入模块名称如:src/libs games/common games/pk_common等") projectFilePath = os.path.join(rootPath, "project.json") projectData = utils.parse_json(projectFilePath) if not isCleanJSList: fileList = [] for module in modules: configPath = os.path.join(rootPath, module, "wxpack.json") if os.path.exists(configPath): commonConfig = utils.parse_json(configPath) else: commonConfig = {} dirname = os.path.join(rootPath, module) fileList += seekFiles(rootPath, commonConfig, dirname, moduleType) projectData['jsList'] = [] projectData['jsList'] = fileList[:] else: projectData['jsList'] = [] # save project.json projectFile = open(projectFilePath, 'w+') try: str = json.dumps(projectData, indent=4, separators=(',', ':')) projectFile.write(str) finally: projectFile.close()
def build(self): Logging.log_msg("star build proto gen proto.js\n") #批处理 try: utils.run_shell('pbjs -t json proto/fishing.proto > json/fishing.js') except Exception as e: raise_known_error("生成proto.js文件失败 msg=%s" % str(e)) #修改文件增加'module.exports =' jsFile = utils.flat_path(os.path.join(self.js_path, 'fishing.js')) f1 = open(jsFile, "r") result = f1.read() f1.close() oResult = "module.exports = %s " % result f2 = open(jsFile, "w") f2.writelines(oResult) f2.close() Logging.log_msg("out file:%s" % jsFile) #将fishing.js文件拷贝到客户端的pb目录 if os.path.exists(self.target_path): shutil.copy(jsFile, self.target_path) Logging.log_msg("move file fishing.js to path : %s \n" % self.target_path) Logging.log_msg("proto build success")
def refreshAssetManager(rootPath, module): # 遍历资源文件夹 assetMap = {} resList = [module] if module == "src/libs": resList.append("src/res") assetFilePath = os.path.join(rootPath, "%s/plistResMap.json" % module) for path in resList: resPath = os.path.join(rootPath, path) print "resPath===" + resPath if not os.path.isdir(resPath): raise_known_error("refreshAssetManager 传入的资源文件夹路径不存在 path=" + resPath) for parent, dirnames, filenames in os.walk(resPath): for filename in filenames: if filename[-6:] == ".plist": plistPath = os.path.join(parent, filename) relPath = os.path.relpath(plistPath, rootPath) relPath = relPath.replace("\\", "/") # pc 上针对斜杆做替换,避免识别不到正确的文件路径 print "plist===" + plistPath # 读取 plist plistMap = plistlib.readPlist(plistPath) frameList = plistMap.get("frames", None) if (frameList != None): for key in frameList: if key[-4:] == ".png": assetMap[key] = relPath with open(assetFilePath, "w+") as f: json.dump(assetMap, f)
def __init__(self, src, dst, rm_src, exclude_cfg, do_copy, quiet=False): self.src_path = utils.flat_path(src) if not os.path.exists(self.src_path): raise_known_error('%s 不存在' % self.src_path, KnownError.ERROR_WRONG_ARGS) if not dst: if os.path.isdir(src): self.dst_path = self.src_path else: self.dst_path = os.path.dirname(self.src_path) else: self.dst_path = utils.flat_path(dst) if os.path.isfile(self.dst_path): raise_known_error('-d 参数必须为文件夹', KnownError.ERROR_WRONG_ARGS) self.dst_is_src = (os.path.isdir(self.src_path) and self.src_path == self.dst_path ) self.rm_src = rm_src self.do_copy = do_copy self.quiet = quiet if exclude_cfg is None: self.exclude_cfg = None elif isinstance(exclude_cfg, list): self.exclude_cfg = self.convert_rules(exclude_cfg) else: self.exclude_cfg = self.parse_exclude_cfg(exclude_cfg)
def check_cfg(self, cfg): if cfg is None or len(cfg) == 0: # 没有需要检查的配置 return for value in cfg: if not self.cfg.has_key(value): raise_known_error('没有配置 %s' % value, KnownError.ERROR_WRONG_CONFIG)
def modify_files(self, cfg): for item in cfg: file_path = utils.flat_path( os.path.join(self.proj_path, item['file'])) if not os.path.isfile(file_path): raise_known_error('%s 不存在' % file_path, KnownError.ERROR_PATH_NOT_FOUND) self._modify_file(file_path, item['replace'])
def createSubPackageByModule(self, module, outputDir): content = "if(isWeb()){\n" classes = [] search_path = os.path.join(self.proj_path, "games", module) if not os.path.exists(search_path): raise_known_error("module not found == %s" % search_path) # 注册 window 全局变量 for parent, dirnames, filenames in os.walk(search_path): for filename in filenames: if filename[-3:] == ".js": classname = filename[:-3] classes.append(classname) if classname == "game": continue if "manifest" in classname: continue content += "window." + classname + "=" + classname + "\n" # 注册GameManager for classname in classes: if "client_" + module == classname or module + "_client" == classname: content += "GameManager.registerGameClient(\"" + module + "\", " + classname + ");\n" if "rule_" + module == classname or module + "_rule" == classname: content += "GameManager.registerRuleClass(\"" + module + "\", " + classname + ");\n" if "config_" + module == classname or module + "_config" == classname: content += "GameManager.registerReplay(\"" + module + "\", " + classname + ");\n" content += "}" # 写入头文件 filepath = os.path.join(self.proj_path, "games", "web_game", module + "_head.js") if os.path.exists(os.path.dirname(filepath)): shutil.rmtree(os.path.dirname(filepath)) os.makedirs(os.path.dirname(filepath)) with open(filepath, "w+") as file_object: try: file_object.write(content) except Exception as e: raise_known_error("写入文件失败 = %s" % filepath) temp_public_path = outputDir sub_game_file = os.path.join(temp_public_path, module + "_game.js") self.games_path = os.path.join(self.proj_path, "games") jsList = self.getCompileJsListByModule(module) self.buildAntFile(jsList, sub_game_file, module) # 拷贝游戏资源 cfg_config = { "from": ".", "to": ".", "exclude": ["*.js$", "TexturePackerRes", ".git", ".gitgnore"] } excopy.copy_files_with_config(cfg_config, search_path, temp_public_path) # 删除web_games文件夹 if os.path.exists(os.path.dirname(filepath)): shutil.rmtree(os.path.dirname(filepath))
def _parse_cfg(self, cfg_path): if not os.path.isfile(cfg_path): raise_known_error('SDK 配置文件 %s 不存在' % cfg_path, KnownError.ERROR_PATH_NOT_FOUND) f = open(cfg_path) ret = json.load(f) f.close() return ret
def check_environment_variable(var): ''' Checking the environment variable, if found then return it's value, else raise error ''' value = None try: value = os.environ[var] except Exception: raise_known_error("环境变量 %s 不存在" % var, KnownError.ERROR_ENV_VAR_NOT_FOUND) return value
def run_shell(cmd, cwd=None, quiet=False): if not quiet: Logging.log_msg('Running command: %s\n' % cmd) p = subprocess.Popen(cmd, shell=True, cwd=cwd) p.wait() if p.returncode: raise_known_error('Command %s failed' % cmd, p.returncode) return p.returncode
def __init__(self, args): self.src_file = utils.flat_path(args.src_file) if not os.path.isfile(self.src_file): raise_known_error('文件 %s 不存在' % self.src_file, KnownError.ERROR_PATH_NOT_FOUND) if args.dst_file: self.dst_file = utils.flat_path(args.dst_file) else: name, ext = os.path.splitext(self.src_file) self.dst_file = '%s_new%s' % (name, ext) Logging.debug_msg("原始文件路径:%s" % self.src_file) Logging.debug_msg("输出文件路径:%s" % self.dst_file)
def run_shell(cmd, cwd=None, quiet=False): if not quiet: cwd_info = '' if cwd: cwd_info = ' (cwd path : %s) ' % cwd Logging.log_msg('Running command%s: %s\n' % (cwd_info, cmd)) p = subprocess.Popen(cmd, shell=True, cwd=cwd) p.wait() if p.returncode: raise_known_error('Command %s failed' % cmd, p.returncode) return p.returncode
def build_creator_proj(self): Logging.debug_msg('开始构建creator项目') try: if sys.platform == "win32": utils.run_shell( 'cd /d %s & CocosCreator.exe --path %s --build "platform=android;debug=false"' % (self.creator_exe_path, self.creator_proj_path)) else: creator_path = '/Applications/CocosCreator.app/Contents/MacOS' utils.run_shell( 'pushd "%s";CocosCreator --path %s --build "platform=android;debug=false";popd' % (creator_path, self.creator_proj_path)) except Exception as e: raise_known_error("Creator 项目命令行构建失败 msg=%s" % str(e)) Logging.debug_msg('构建creator项目完成')
def parse_exclude_cfg(self, cfg_file): cfg_full_path = utils.flat_path(cfg_file) if not os.path.isfile(cfg_full_path): raise_known_error("%s 文件不存在" % cfg_full_path, KnownError.ERROR_PATH_NOT_FOUND) ret = None try: f = open(cfg_full_path) ret = json.load(f) f.close() ret = self.convert_rules(ret) except: raise_known_error('解析 %s 失败' % cfg_full_path, KnownError.ERROR_PARSE_FILE) return ret
def build_creator_proj(self): Logging.debug_msg('开始构建creator项目') Logging.debug_msg(self.creator_proj_parth) creator_exe_path = utils.check_environment_variable('CREATOR_PATH') try: if sys.platform == "win32": utils.run_shell( 'cd /d %s & CocosCreator.exe --path %s --build "platform=wechatgame;debug=false"' % (creator_exe_path, self.creator_proj_parth)) else: creator_path = '/Applications/CocosCreator.app/Contents/MacOS/' utils.run_shell( '%sCocosCreator --path %s --build "platform=wechatgame;debug=false"' % (creator_path, self.creator_proj_parth)) except Exception as e: raise_known_error("Creator 项目命令行构建失败 msg=%s" % str(e)) Logging.debug_msg('构建creator项目完成')
def setGradleConfig(self, rollback_obj, cfg_dir, apk_cfg_info, apk_name): print("set gradle config") gradle_config_path = utils.flat_path( os.path.join(self.proj_android_path, 'launcher/config.gradle')) cfg_file_path = utils.flat_path(os.path.join(cfg_dir, "package.json")) if sys.platform == "win32": cfg_file_path = cfg_file_path.replace("\\", "/") rollback_obj.record_file(gradle_config_path) # 设置 packagePath 路径 data = [] f = open(gradle_config_path) lines = f.readlines() f.close() for line in lines: if (line.find('def packagePath =') == 0): line = 'def packagePath = \"%s\"' % cfg_file_path + '\n' data.append(line) f = open(gradle_config_path, "w") f.writelines(data) f.close() apk_cfg_info = utils.parse_json(cfg_file_path) keystore_path = utils.flat_path( os.path.join( cfg_dir, apk_cfg_info[PackAPK.CFG_SIGN][PackAPK.CFG_SIGN_FILE])) if sys.platform == "win32": keystore_path = keystore_path.replace("\\", "/") apk_cfg_info['sign']['storefile'] = keystore_path apk_cfg_info['sign']['output_apk_dir'] = self.output_path apk_cfg_info['sign']['output_apk_name'] = apk_name # save package.json packageFile = open(cfg_file_path, 'w+') try: str = json.dumps(apk_cfg_info, ensure_ascii=False, indent=4, separators=(',', ':')) packageFile.write(str) except: raise_known_error("write package.json error!") finally: packageFile.close()
def prepare_sdk(self): lib_projs = [":libraryAndroid"] remove_libs = [] sdk_names = [] sdk_names.extend(SDKManager.DEFAULT_LIBRARIES) if len(self.sdks_cfg.keys()) > 0: sdk_names.extend(self.sdks_cfg.keys()) for sdk in sdk_names: sdk_proj_path = '../library.%s.android' % sdk.lower() sdk_proj_name = ':lib%sAndroid' % sdk sdk_full_path = utils.flat_path( os.path.join(self.android_proj_path, sdk_proj_path)) if not os.path.isdir(sdk_full_path): raise_known_error('SDK 文件夹 %s 不存在' % sdk_full_path, KnownError.ERROR_PATH_NOT_FOUND) lib_projs.append(sdk_proj_name) if sdk == "Chat" or sdk == "YouquShare": # 客服和有趣分享不需要特殊处理 continue sdk_cfg = {} if self.sdks_cfg.has_key(sdk): sdk_cfg = self.sdks_cfg[sdk] if sdk == "Getui": sdk_cfg = self.setGetuiParams(sdk_cfg, sdk_full_path) sdk_obj = BaseSDK(self.file_recorder, self.game_pkg_name, sdk_cfg, sdk_full_path, self) sdk_obj.do_steps() remove_sdks = sdk_obj.get_remove_sdks() remove_libs.extend(remove_sdks) if self.remove_weixin: remove_libs.append("libWeixinAndroid") for remove_lib in remove_libs: check_str = ":lib%sAndroid" % remove_lib if check_str in lib_projs: lib_projs.remove(check_str) # 修改 config.gradle 文件 self._modify_proj_gradle_config(lib_projs)
def __init__(self, args): self.batch_cfg_file = utils.flat_path(args.proj_cfg) if not os.path.isfile(self.batch_cfg_file): raise_known_error("文件 %s 不存在" % self.batch_cfg_file, KnownError.ERROR_PATH_NOT_FOUND) self.root_dir = os.path.dirname(self.batch_cfg_file) cur_time_str = datetime.datetime.fromtimestamp( time.time()).strftime('%Y%m%d') self.output_path = os.path.join(self.root_dir, 'output', cur_time_str) #配置文件数据 self.batch_info = self.parse_json(self.batch_cfg_file) if not self.batch_info: raise_known_error('解析文件 %s 失败' % self.batch_cfg_file, KnownError.ERROR_PARSE_FILE) Logging.debug_msg('使用配置文件 : %s' % self.batch_cfg_file) Logging.debug_msg('----------------\n')
def build_apk_gradle(self, rollback_obj, cfg_dir, apk_cfg_info, apk_name): # 最终 apk 文件名格式为:GAMENAME_PKGNAME_APPID_CHANNELID_VERNAME_VERCODE.apk # Logging.debug_msg('修改apk文件名 game_name=%s pkg_name=%s app_id=%s channel_id=%s ver_name=%s ver_code=%s' % (game_name, pkg_name, app_id, channel_id, ver_name, ver_code)) # 修改签名文件 Logging.debug_msg('修改签名文件') self.setGradleConfig(rollback_obj, cfg_dir, apk_cfg_info, apk_name) try: if sys.platform == "win32": utils.run_shell( 'cd /d %s & set ANDROID_HOME="%s" & gradlew clean & gradlew aR --stacktrace' % (self.proj_android_path, self.sdk_root)) else: utils.run_shell( 'pushd "%s";export ANDROID_HOME="%s";./gradlew clean;./gradlew aR --stacktrace;popd' % (self.proj_android_path, self.sdk_root)) except Exception as e: raise_known_error("gradle 命令行打包失败 msg=%s" % str(e)) Logging.debug_msg('gradle配置文件修改完成')
def _do_remove_agora(self, rollback_obj): for f in PackAPK.AGORA_LIBS: agora_lib_path = utils.flat_path( os.path.join(self.library_android_path, f)) if not os.path.isfile(agora_lib_path): raise_known_error('Agora 库文件: %s 不存在' % agora_lib_path, KnownError.ERROR_PATH_NOT_FOUND) # 记录库文件,方便回滚 rollback_obj.record_file(agora_lib_path) # 删除库文件 os.remove(agora_lib_path) # 需要替换 wlgame.so src_so = utils.flat_path( os.path.join(self.library_android_path, PackAPK.NO_AGORA_SO)) if not os.path.isfile(src_so): raise_known_error('不包含 Agora 的库文件: %s 不存在' % src_so, KnownError.ERROR_PATH_NOT_FOUND) replace_so = utils.flat_path( os.path.join(self.library_android_path, PackAPK.NO_AGORA_NEED_REPLACE_SO)) if not os.path.isfile(replace_so): raise_known_error('库文件: %s 不存在' % replace_so, KnownError.ERROR_PATH_NOT_FOUND) rollback_obj.record_file(replace_so) shutil.copy2(src_so, os.path.dirname(replace_so)) # 需要修改 AppActivity.java 文件 java_file = utils.flat_path( os.path.join(self.proj_android_path, "src/weile/games/AppActivity.java")) if not os.path.isfile(java_file): raise_known_error('文件 %s 不存在' % java_file, KnownError.ERROR_PATH_NOT_FOUND) rollback_obj.record_file(java_file) f = open(java_file) lines = f.readlines() f.close() pattern1 = "agora-rtc-sdk-jni" pattern2 = "apm-plugin-agora-cocos2dx" new_lines = [] for l in lines: if l.find(pattern1) >= 0 or l.find(pattern2) >= 0: l = '// ' + l new_lines.append(l) f = open(java_file, 'w') f.writelines(new_lines) f.close()
def __init__(self, args): self.no_rollback = args.no_rollback self.no_encrypt = args.no_encrypt self.no_build_creator = args.no_build_creator self.root_dir = os.path.dirname("./") # self.temp_dir = os.path.join(self.root_dir, 'temp') cur_time_str = datetime.datetime.fromtimestamp( time.time()).strftime('%Y%m%d_%H%M%S') self.output_path = os.path.join(self.root_dir, 'output', cur_time_str) # 检查Creator的安装目录跟工程目录 self.creator_proj_parth = utils.flat_path( os.path.join(self.root_dir, '../../')) if sys.platform == "win32": self.creator_exe_path = utils.check_environment_variable( 'CREATOR_PATH') if not os.path.isdir(self.creator_exe_path): raise_known_error("环境变量 CREATOR_PATH 未设置") self.proj_parth = utils.flat_path( os.path.join(os.path.dirname(__file__), '../../../../build/jsb-link'))
def get_file_hash(filePath, isBinary, hashFunc): if not os.path.isfile(filePath): raise_known_error('文件 %s 不存在' % filePath, KnownError.ERROR_PATH_NOT_FOUND) if isBinary: # 二进制文件使用 rb 方式读取 f = open(filePath, 'rb') else: # 文本文件使用 rU 方式读取,保证不受换行符影响 f = open(filePath, 'rU') content = f.read() f.close() cmd = getattr(hashlib, hashFunc.lower()) if not cmd: raise_known_error('未知的 hash 类型: %s' % hashFunc, KnownError.ERROR_WRONG_ARGS) return cmd(content).hexdigest().upper()
def __init__(self, args): # 配置文件 self.batch_cfg_file = utils.flat_path(args.proj_cfg) if not os.path.isfile(self.batch_cfg_file): raise_known_error("文件 %s 不存在" % self.batch_cfg_file, KnownError.ERROR_PATH_NOT_FOUND) self.root_dir = os.path.dirname(self.batch_cfg_file) self.batch_info = self._parse_json(self.batch_cfg_file) if not self.batch_info: raise_known_error('解析文件 %s 失败' % self.batch_cfg_file, KnownError.ERROR_PARSE_FILE) self.app_id = self.batch_info['appid'] self.channel_id = self.batch_info['channel'] self.proj_parth = utils.flat_path( os.path.join(self.root_dir, self.batch_info['proj_root'])) self.pack_parth = utils.flat_path( os.path.join(self.root_dir, self.batch_info['pack_root'])) # 是否需要重编creator self.rebuild_creator = args.rebuild_creator if self.rebuild_creator: # 检查Creator的安装目录 self.creator_exe_path = utils.check_environment_variable( 'CREATOR_PATH') if not os.path.isdir(self.creator_exe_path): raise_known_error("环境变量 CREATOR_PATH 未设置") self.creator_proj_path = utils.flat_path( os.path.join(self.proj_parth, '../../')) self.encrypt_res = args.encrypt_res Logging.debug_msg('是否重新编译creator工程 : %s' % self.rebuild_creator) Logging.debug_msg('是否加密图片资源 : %s' % self.encrypt_res) Logging.debug_msg('------------------------------------\n')
def build_creator_proj(self): Logging.debug_msg('开始构建creator项目') Logging.debug_msg(self.creator_proj_path) try: # 删除之前构建生成的文件夹 if os.path.isdir(self.proj_parth): shutil.rmtree(self.proj_parth) json_file = os.path.join(self.creator_proj_path, "settings/wechatgame.json") loads = self.readJson(json_file) loads["startSceneAssetBundle"] = False self.writeJson(json_file, loads) # https://docs.cocos.com/creator/manual/en/publish/publish-in-command-line.html buildoptions = ";".join([ "platform=wechatgame", "buildPath=build", "debug=false", "sourceMaps=false", "md5Cache=true", "mainCompressionType=merge_all_json", "mainIsRemote=false" ]) paramFmt = '--path {path} --build "{options}"' params = paramFmt.format(path=self.creator_proj_path, options=buildoptions) if sys.platform == "win32": creator_exe_path = utils.check_environment_variable( 'CREATOR_PATH') cmdline = 'cd /d "%s" & CocosCreator.exe %s' % ( creator_exe_path, params) utils.run_shell(cmdline) else: creator_path = '/Applications/CocosCreator/Creator/2.4.3/CocosCreator.app/Contents/MacOS/CocosCreator' utils.run_shell('%s %s' % (creator_path, params)) except Exception as e: raise_known_error("Creator 项目命令行构建失败 msg=%s" % str(e)) Logging.debug_msg('构建creator项目完成')
def copyResourceByJsModule(rootPath, modulePath, desPath, moduleType=None): if not os.path.exists(modulePath): raise_known_error("module path not found %s" % modulePath, KnownError.ERROR_PATH_NOT_FOUND) if not os.path.exists(desPath): raise_known_error("desPath path not found %s" % desPath, KnownError.ERROR_PATH_NOT_FOUND) # 拷贝所有非 js 文件 excludes = ["TexturePackerRes", "preload_res"] for parent, dirnames, filenames in os.walk(modulePath): for filename in filenames: if filename[:1] == ".": continue if filename[-3:] == ".js": continue isExclude = False for exclude in excludes: if exclude in parent: isExclude = True break if isExclude: continue srcfile = os.path.join(parent, filename) relpath = os.path.relpath(srcfile, rootPath) #过滤指定资源文件 if isFilterFile(moduleType, srcfile): continue reldirname = os.path.dirname(relpath) desdirname = os.path.join(desPath, reldirname) desfile = os.path.join(desdirname, filename) print("copy %s to %s" % (srcfile, desfile)) if not os.path.exists(desdirname): os.makedirs(desdirname) shutil.copyfile(srcfile, desfile)
def createManifestFile(rootPath, module, moduleType=None, specVer=None): if os.path.exists(rootPath) == False: raise_known_error("root path is not found ===" + rootPath, KnownError.ERROR_PATH_NOT_FOUND) configPath = os.path.join(rootPath, module, "wxpack.json") if not os.path.exists(configPath): raise_known_error("%s not found" % configPath, KnownError.ERROR_PATH_NOT_FOUND) commonConfig = utils.parse_json(configPath) if specVer is None: if not commonConfig.has_key('version'): raise_known_error("%s/wxpack.json 必须包含version参数" % module) version = commonConfig.get("version", 1) else: version = specVer dirname = os.path.join(rootPath, module) basename = os.path.basename(dirname) filename = os.path.join(dirname, "manifest_" + basename + ".js") if os.path.exists(dirname) == False: raise_known_error("module path is not exists ===" + module, KnownError.ERROR_PATH_NOT_FOUND) codeStr = "function manifest_" codeStr += basename codeStr += "() {\nreturn " data = {} data["version"] = version fileList = seekFiles(rootPath, commonConfig, dirname, moduleType) data["jslist"] = fileList str = json.dumps(data, indent=4, separators=(',', ': ')) codeStr += str codeStr += "}\n" codeStr += 'manifest_' codeStr += basename codeStr += "()" file_object = open(filename, 'w+') try: file_object.write(codeStr) finally: file_object.close() # 生成 plist 资源映射表 refreshAssetManager(rootPath, module)
def _copy_game_common_parts(self, parts, assets_path): if not parts or len(parts) == 0: return for k in parts: if k not in PackAPK.GAME_COMMON_PART_VALUES: raise_known_error('game_common_parts 中配置 %s 无效' % k, KnownError.ERROR_WRONG_ARGS) if not os.path.isdir(self.games_root_path): raise_known_error('文件夹 %s 不存在' % self.games_root_path, KnownError.ERROR_PATH_NOT_FOUND) # 通用组件的文件划分配置文件 cfg_file = utils.flat_path( os.path.join(self.games_root_path, "common/for-pack/pack-cfg.json")) if not os.path.isfile(cfg_file): raise_known_error('配置文件 %s 不存在' % cfg_file, KnownError.ERROR_PATH_NOT_FOUND) cfg_info = self._parse_json(cfg_file) base_exclude = ['**/.DS_Store', '*.git'] cp_cfgs = [] for k in parts: if k == "common": for d in PackAPK.DEFAULT_GAMES_DIRS: exclude = [] exclude.extend(base_exclude) exclude.extend(self._conv_rules(cfg_info['exclude'], d)) exclude.extend( self._conv_rules(cfg_info['pk_common']['include'], d)) exclude.extend( self._conv_rules(cfg_info['mj_common']['include'], d)) cp_cfgs.append({ 'from': d, 'to': 'games/%s' % d, 'exclude': exclude }) else: for d in PackAPK.DEFAULT_GAMES_DIRS: include = self._conv_rules(cfg_info[k]['include'], d) if len(include) > 0: cp_cfgs.append({ 'from': d, 'to': 'games/%s' % d, 'include': include }) for c in cp_cfgs: excopy.copy_files_with_config(c, self.games_root_path, assets_path)
def __init__(self, args): self.batch_cfg_file = utils.flat_path(args.proj_cfg) if not os.path.isfile(self.batch_cfg_file): raise_known_error("文件 %s 不存在" % self.batch_cfg_file, KnownError.ERROR_PATH_NOT_FOUND) self.no_rollback = args.no_rollback self.root_dir = os.path.dirname(self.batch_cfg_file) cur_time_str = datetime.datetime.fromtimestamp( time.time()).strftime('%Y%m%d_%H%M%S') self.output_path = os.path.join(self.root_dir, 'output', cur_time_str) #配置文件数据 self.batch_info = self._parse_json(self.batch_cfg_file) if not self.batch_info: raise_known_error('解析文件 %s 失败' % self.batch_cfg_file, KnownError.ERROR_PARSE_FILE) # 检查 android sdk 环境变量 self.sdk_root = utils.flat_path( utils.check_environment_variable('ANDROID_SDK_ROOT')) self.build_result = {} cur_dir = os.path.dirname(__file__) self.proj_parth = utils.flat_path( os.path.join(cur_dir, '../../../jsb-default')) self.proj_android_path = utils.flat_path( os.path.join(self.proj_parth, 'project_android_20')) if not os.path.isdir(self.proj_android_path): raise_known_error("未找到 Android 工程文件夹 %s" % self.proj_android_path) self.android_manifest = os.path.join( self.proj_android_path, 'launcher/src/main/AndroidManifest.xml') self.java_files = [] for parent, dirs, files in os.walk( utils.flat_path( os.path.join(self.proj_android_path, 'unityLibrary/src/main/java'))): for f in files: filename, ext = os.path.splitext(f) if ext.lower() == '.java': self.java_files.append(os.path.join(parent, f)) Logging.debug_msg('使用配置文件 : %s' % self.batch_cfg_file) Logging.debug_msg('是否禁用还原 : %s' % self.no_rollback) Logging.debug_msg('Android 工程路径 : %s' % self.proj_android_path) Logging.debug_msg('----------------\n')
if __name__ == "__main__": from argparse import ArgumentParser parser = ArgumentParser(prog="ResEncrypt", description=utils.get_sys_encode_str("对资源文件进行加密和压缩")) parser.add_argument("-s", "--src", dest="src", required=True, help=utils.get_sys_encode_str("指定源文件或者文件夹。")) parser.add_argument("-d", "--dst", dest="dst", help=utils.get_sys_encode_str("指定目标路径。默认与源文件位置相同。")) parser.add_argument("--rm-src", dest="rm_src", action="store_true", help=utils.get_sys_encode_str("删除原始的文件")) parser.add_argument("--copy", dest="do_copy", action="store_true", help=utils.get_sys_encode_str("指定拷贝非加密文件")) parser.add_argument("--cfg", dest="exclude_cfg", help=utils.get_sys_encode_str("指定一个配置文件,这个文件用于配置排除某些资源文件")) (args, unknown) = parser.parse_known_args() # record the start time begin_time = time.time() try: if len(unknown) > 0: raise_known_error('未知参数 : %s' % unknown, KnownError.ERROR_WRONG_ARGS) encryptor = ResEncrypt(args.src, args.dst, args.rm_src, args.exclude_cfg, args.do_copy) encryptor.do_encrypt() except KnownError as e: # a known exception, exit with the known error number sys.exit(e.get_error_no()) except Exception: raise finally: # output the spend time end_time = time.time() Logging.log_msg('\n总共用时: %.2f 秒\n' % (end_time - begin_time))
dest="no_rollback", action='store_true', help=utils.get_sys_encode_str("若指定此参数,则不执行还原操作")) parser.add_argument("-v", "--version", dest="version", help=utils.get_sys_encode_str("指定配置文件")) (args, unknown) = parser.parse_known_args() # record the start time begin_time = time.time() try: if sys.platform == "win32": creator_exe_path = utils.check_environment_variable('CREATOR_PATH') if not os.path.isdir(creator_exe_path): raise_known_error("环境变量 CREATOR_PATH 未设置") if len(unknown) > 0: raise_known_error('未知参数 : %s' % unknown, KnownError.ERROR_WRONG_ARGS) print(args) packer = PackAPK(args) packer.do_build(args.no_build_creator) except KnownError as e: # a known exception, exit with the known error number sys.exit(e.get_error_no()) except Exception: raise finally: # output the spend time end_time = time.time() Logging.log_msg('\n总共用时: %.2f 秒\n' % (end_time - begin_time))