Example #1
0
 def gen_prebuilt_module(self, module_name):
     print("generate prebuilt module : %s" % module_name)
     module_info = self.modules_info[module_name]
     copy_cfg = {
         "from" : module_info[ModuleOrganizer.KEY_MODULE_FROM_DIR],
         "to": module_info[ModuleOrganizer.KEY_MODULE_TARGET_DIR]
     }
     excopy.copy_files_with_config(copy_cfg, self.src_root, self.dst_root)
Example #2
0
 def gen_prebuilt_module(self, module_name):
     print("generate prebuilt module : %s" % module_name)
     module_info = self.modules_info[module_name]
     copy_cfg = {
         "from": module_info[ModuleOrganizer.KEY_MODULE_FROM_DIR],
         "to": module_info[ModuleOrganizer.KEY_MODULE_TARGET_DIR]
     }
     excopy.copy_files_with_config(copy_cfg, self.src_root, self.dst_root)
    def build_android(self, language):
        # build .a for android
        console_dir = os.path.join(self.engine_dir, CONSOLE_PATH)
        cmd_path = os.path.join(console_dir, "cocos")
        proj_path = os.path.join(self.engine_dir, "tests/%s-tests" % language)

        # Add multi ABI in Application.mk
        mk_file = os.path.join(proj_path, MK_PATH)
        f = open(mk_file)
        file_content = f.read()
        f.close()

        self.modify_mk(mk_file)

        # build it
        build_cmd = "%s compile -s %s -p android --ndk-mode release -j 4" % (cmd_path, proj_path)
        run_shell(build_cmd)

        f = open(mk_file, "w")
        f.write(file_content)
        f.close()

        # copy .a to prebuilt dir
        obj_dir = os.path.join(proj_path, ANDROID_A_PATH)
        prebuilt_dir = os.path.join(self.tool_dir, "prebuilt", "android")
        copy_cfg = {
            "from": obj_dir,
            "to": prebuilt_dir,
            "include": [
                "*.a$"
            ]
        }
        excopy.copy_files_with_config(copy_cfg, obj_dir, prebuilt_dir)

        if not self.disable_strip:
            # strip the android libs
            ndk_root = os.environ["NDK_ROOT"]
            if os_is_win32():
                if self.is_32bit_windows():
                    bit_str = ""
                else:
                    bit_str = "-x86_64"

                sys_folder_name = "windows%s" % bit_str
            elif os_is_mac():
                sys_folder_name = "darwin-x86_64"

            # strip arm libs
            strip_cmd_path = os.path.join(ndk_root, "toolchains/arm-linux-androideabi-4.8/prebuilt/%s/arm-linux-androideabi/bin/strip" % sys_folder_name)
            if os.path.exists(strip_cmd_path):
                strip_cmd = "%s -S %s/armeabi*/*.a" % (strip_cmd_path, prebuilt_dir)
                run_shell(strip_cmd)

            # strip x86 libs
            strip_cmd_path = os.path.join(ndk_root, "toolchains/x86-4.8/prebuilt/%s/i686-linux-android/bin/strip" % sys_folder_name)
            if os.path.exists(strip_cmd_path) and os.path.exists(os.path.join(prebuilt_dir, "x86")):
                strip_cmd = "%s -S %s/x86/*.a" % (strip_cmd_path, prebuilt_dir)
                run_shell(strip_cmd)
Example #4
0
    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))
Example #5
0
 def _modify_res(self, apk_cfg_info, cfg_dir, rollback_obj):
     #备份res
     rollback_obj.record_folder(
         os.path.join(self.proj_android_path, 'launcher/src/main/res'))
     for p in apk_cfg_info[PackAPK.CFG_JAVA_RES].split(','):
         java_res_path = utils.flat_path(os.path.join(cfg_dir, p.strip()))
         copy_cfg = {'from': '.', 'to': 'res', 'exclude': ['**/.DS_Store']}
         res_path = utils.flat_path(
             os.path.join(self.proj_android_path, 'launcher/src/main'))
         excopy.copy_files_with_config(copy_cfg, java_res_path, res_path)
Example #6
0
    def do_build(self, no_build_creator):
        dst = utils.flat_path('./pack_temp/')
        print(dst)
        # 编译creator工程
        if not no_build_creator:
            self.build_creator_proj()

        cfgPath = utils.flat_path('./CfgPackage.js')
        #获得版本号
        f = open(cfgPath, 'rU')
        content = f.read()
        f.close()
        pattern = re.compile(r'\[([^\[\]]*)\]')  # 查找数字
        tb = pattern.findall(content)
        versionStr = tb[0]
        versionStr = versionStr.replace(",", ".")
        versionStr = versionStr.replace(" ", "")
        print('version: ' + versionStr)
        time.sleep(1)

        packArgs = {}
        packArgs['confuseResImport'] = False
        packArgs['exclude'] = False
        packArgs['compressPng'] = False
        packArgs['encrytPng'] = True
        packArgs['encrytJS'] = True
        packArgs['cfgPackagePath'] = cfgPath
        packArgs['nativePath'] = utils.flat_path('./native.js')
        packArgs['zipDir'] = ''
        packArgs['minigame'] = False
        genRes.start(versionStr, self.proj_parth, dst, packArgs)

        print("+++++++++++++++++++++sync ios-assets")
        iosPath = utils.flat_path(
            os.path.join(os.path.dirname(__file__),
                         '../../../../ios-assets/src'))
        if os.path.isdir(iosPath):
            time.sleep(0.01)
            shutil.rmtree(iosPath)
            time.sleep(0.01)

        iosPath = utils.flat_path(
            os.path.join(os.path.dirname(__file__),
                         '../../../../ios-assets/res'))
        if os.path.isdir(iosPath):
            time.sleep(0.01)
            shutil.rmtree(iosPath)
            time.sleep(0.01)

        iosPath = utils.flat_path(
            os.path.join(os.path.dirname(__file__), '../../../../ios-assets'))
        # 同步到ios-assets
        copy_cfg = {'from': '.', 'to': '.', 'exclude': ['**/.DS_Store']}
        # 将构建出来的res、src、subpackages目录拷贝到打包目录
        excopy.copy_files_with_config(copy_cfg, dst + '/mainPackage', iosPath)
Example #7
0
    def build_android(self):
        # build .so for android
        language = "lua"

        console_dir = os.path.join(self.engine_dir, CONSOLE_PATH)
        cmd_path = os.path.join(console_dir, "cocos")
        proj_name = "My%sGame" % language
        proj_path = os.path.join(self.engine_dir, proj_name)
        if os.path.exists(proj_path):
            shutil.rmtree(proj_path)

        # create a runtime project
        create_cmd = "%s new -l %s -t runtime -d %s %s" % (cmd_path, language, self.engine_dir, proj_name)
        run_shell(create_cmd)

        # Add multi ABI in Application.mk
        mk_file = os.path.join(proj_path, MK_PATH)
        self.modify_mk(mk_file)

        # build it
        build_cmd = "%s compile -s %s -p android --ndk-mode release -j 4" % (cmd_path, proj_path)
        run_shell(build_cmd)

        # copy .a to prebuilt dir
        obj_dir = os.path.join(proj_path, ANDROID_A_PATH)
        prebuilt_dir = os.path.join(self.tool_dir, "prebuilt", "android")
        copy_cfg = {
            "from": obj_dir,
            "to": prebuilt_dir,
            "include": [
                "*.a$"
            ]
        }
        excopy.copy_files_with_config(copy_cfg, obj_dir, prebuilt_dir)

        if self.enable_strip:
            # strip the android libs
            ndk_root = os.environ["NDK_ROOT"]
            if os_is_win32():
                if self.is_32bit_windows():
                    bit_str = "x86"
                else:
                    bit_str = "x86_64"

                sys_folder_name = "windows-%s" % bit_str
            elif os_is_mac():
                sys_folder_name = "darwin-x86_64"

            strip_cmd_path = os.path.join(ndk_root, "toolchains/arm-linux-androideabi-4.8/prebuilt/%s/arm-linux-androideabi/bin/strip" % sys_folder_name)
            if os.path.exists(strip_cmd_path):
                strip_cmd = "%s -S %s/armeabi*/*.a" % (strip_cmd_path, prebuilt_dir)
                run_shell(strip_cmd)

        # remove the project
        shutil.rmtree(proj_path)
Example #8
0
    def build_android(self):
        # build .so for android
        language = "lua"

        console_dir = os.path.join(self.engine_dir, CONSOLE_PATH)
        cmd_path = os.path.join(console_dir, "cocos")
        proj_name = "My%sGame" % language
        proj_path = os.path.join(self.engine_dir, proj_name)
        if os.path.exists(proj_path):
            shutil.rmtree(proj_path)

        # create a runtime project
        create_cmd = "%s new -l %s -t runtime -d %s %s" % (
            cmd_path, language, self.engine_dir, proj_name)
        run_shell(create_cmd)

        # Add multi ABI in Application.mk
        mk_file = os.path.join(proj_path, MK_PATH)
        self.modify_mk(mk_file)

        # build it
        build_cmd = "%s compile -s %s -p android --ndk-mode release -j 4" % (
            cmd_path, proj_path)
        run_shell(build_cmd)

        # copy .a to prebuilt dir
        obj_dir = os.path.join(proj_path, ANDROID_A_PATH)
        prebuilt_dir = os.path.join(self.tool_dir, "prebuilt", "android")
        copy_cfg = {"from": obj_dir, "to": prebuilt_dir, "include": ["*.a$"]}
        excopy.copy_files_with_config(copy_cfg, obj_dir, prebuilt_dir)

        if self.enable_strip:
            # strip the android libs
            ndk_root = os.environ["NDK_ROOT"]
            if os_is_win32():
                if self.is_32bit_windows():
                    bit_str = "x86"
                else:
                    bit_str = "x86_64"

                sys_folder_name = "windows-%s" % bit_str
            elif os_is_mac():
                sys_folder_name = "darwin-x86_64"

            strip_cmd_path = os.path.join(
                ndk_root,
                "toolchains/arm-linux-androideabi-4.8/prebuilt/%s/arm-linux-androideabi/bin/strip"
                % sys_folder_name)
            if os.path.exists(strip_cmd_path):
                strip_cmd = "%s -S %s/armeabi*/*.a" % (strip_cmd_path,
                                                       prebuilt_dir)
                run_shell(strip_cmd)

        # remove the project
        shutil.rmtree(proj_path)
    def build_android(self, language):
        # build .so for android
        if language == "js":
            engine_name = "cocos2d-js"
        else:
            engine_name = "cocos2d-x"

        engine_dir = os.path.join(self.root_dir, engine_name)
        console_dir = os.path.join(engine_dir, CONSOLE_PATH)
        cmd_path = os.path.join(console_dir, "cocos")
        proj_name = "My%sGame" % language
        proj_path = os.path.join(engine_dir, proj_name)
        if os.path.exists(proj_path):
            shutil.rmtree(proj_path)

        # create a runtime project
        create_cmd = "%s new -l %s -t runtime -d %s %s" % (cmd_path, language, engine_dir, proj_name)
        run_shell(create_cmd)

        # Add multi ABI in Application.mk
        mk_file = os.path.join(proj_path, MK_PATH)
        self.modify_mk(mk_file)

        # build it
        build_cmd = "%s compile -s %s -p android --ndk-mode release -j 4" % (cmd_path, proj_path)
        run_shell(build_cmd)

        # copy .so to the template dir
        libs_dir = os.path.join(proj_path, ANDROID_SO_PATH)
        target_libs_dir = os.path.join(self.root_dir, "gen", "cocos", "frameworks", engine_name, "templates", "%s-template-runtime" % language, ANDROID_SO_PATH)
        if os.path.exists(target_libs_dir):
            shutil.rmtree(target_libs_dir)
        shutil.copytree(libs_dir, target_libs_dir)

        # copy .a to prebuilt dir
        obj_dir = os.path.join(proj_path, ANDROID_A_PATH)
        prebuilt_dir = os.path.join(self.root_dir, "gen", "cocos", "frameworks", engine_name, "prebuilt", "android")
        copy_cfg = {
            "from": obj_dir,
            "to": prebuilt_dir,
            "include": [
                "*.a$"
            ]
        }
        excopy.copy_files_with_config(copy_cfg, obj_dir, prebuilt_dir)

        # modify the mk files to prebuilt version
        import gen_prebuilt_mk
        for mk_file in self.android_mks:
            mk_file_path = os.path.join(self.root_dir, mk_file)
            tmp_obj = gen_prebuilt_mk.MKGenerator(mk_file_path, prebuilt_dir, mk_file_path)
            tmp_obj.do_generate()

        # remove the project
        shutil.rmtree(proj_path)
Example #10
0
    def update_resources(self):
        Logging.debug_msg('正在拷贝资源到tmp目录..')
        # 拷贝资源到tmp目录
        for res in self.batch_info['include']:
            if not res:
                continue
            copy_cfg = {'from': res, 'to': res, 'exclude': ['**/.DS_Store']}
            excopy.copy_files_with_config(copy_cfg, self.proj_parth,
                                          self.temp_dir)

        # 先删除CfgPackage.js或CfgPackage.jsc
        scripts_path = utils.flat_path(
            os.path.join(self.temp_dir, 'src/assets/scripts'))
        self.del_js_file(scripts_path, 'CfgPackage')
        self.del_js_file(scripts_path, 'manifest')

        # 替换CfgPackage.js文件
        pack_cfg_path = utils.flat_path(
            os.path.join(self.pack_parth, self.app_id, self.channel_id))
        copy_cfg = {
            'from': 'cfg',
            'to': 'src/assets/scripts',
            'exclude': ['**/.DS_Store']
        }
        excopy.copy_files_with_config(copy_cfg, pack_cfg_path, self.temp_dir)

        Logging.debug_msg('正在生成资源列表的md5信息..')
        # 生成资源列表的md5信息
        assetsObj = self.manifest_obj['assets']
        self.get_file_path_md5(self.temp_dir, assetsObj)

        # 替换掉文件 manifest.js
        tmp_str = "(function() { window.CustomManifestAssets = holdString})();"
        tmp_str = tmp_str.replace("holdString", json.dumps(assetsObj))
        src_path = utils.flat_path(os.path.join(self.temp_dir, 'src'))
        manifest_js_path = utils.flat_path(
            os.path.join(src_path, 'assets/scripts/manifest.js'))
        file_m = open(manifest_js_path, "wb")
        file_m.writelines(tmp_str)
        file_m.close()

        # 重新计算manifest.js的md5值
        rel_path = 'src/assets/scripts/manifest.js'
        assetsObj[rel_path] = {
            'size': os.path.getsize(manifest_js_path),
            'md5': self.get_file_md5(manifest_js_path)
        }

        Logging.debug_msg('生成project.manifest文件..')
        # 创建project.manifest
        version_manifest = utils.flat_path(
            os.path.join(self.temp_dir, 'project.manifest'))
        file_m = open(version_manifest, "wb")
        file_m.writelines(json.dumps(self.manifest_obj))
        file_m.close()
Example #11
0
    def build_android(self):
        # build .a for android
        console_dir = os.path.join(self.engine_dir, CONSOLE_PATH)
        cmd_path = os.path.join(console_dir, "cocos")
        proj_path = os.path.join(self.engine_dir, TESTS_PROJ_PATH)

        # Add multi ABI in Application.mk
        mk_file = os.path.join(proj_path, MK_PATH)
        f = open(mk_file)
        file_content = f.read()
        f.close()

        self.modify_mk(mk_file)

        # build it
        build_cmd = "%s compile -s %s -p android --ndk-mode release -j 4" % (cmd_path, proj_path)
        run_shell(build_cmd)

        f = open(mk_file, "w")
        f.write(file_content)
        f.close()

        # copy .a to prebuilt dir
        obj_dir = os.path.join(proj_path, ANDROID_A_PATH)
        prebuilt_dir = os.path.join(self.tool_dir, "prebuilt", "android")
        copy_cfg = {
            "from": obj_dir,
            "to": prebuilt_dir,
            "include": [
                "*.a$"
            ]
        }
        excopy.copy_files_with_config(copy_cfg, obj_dir, prebuilt_dir)

        if not self.disable_strip:
            # strip the android libs
            ndk_root = os.environ["NDK_ROOT"]
            if os_is_win32():
                if self.is_32bit_windows():
                    bit_str = ""
                else:
                    bit_str = "-x86_64"

                sys_folder_name = "windows%s" % bit_str
            elif os_is_mac():
                sys_folder_name = "darwin-x86_64"

            strip_cmd_path = os.path.join(ndk_root, "toolchains/arm-linux-androideabi-4.8/prebuilt/%s/arm-linux-androideabi/bin/strip" % sys_folder_name)
            if os.path.exists(strip_cmd_path):
                strip_cmd = "%s -S %s/armeabi*/*.a" % (strip_cmd_path, prebuilt_dir)
                run_shell(strip_cmd)
Example #12
0
    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)
Example #13
0
    def copy_template(self):
        for item in self.config_json[
                CocosBinTemplateGenerator.KEY_COPY_CONFIG]:
            excopy.copy_files_with_config(item, self.repo_x, self.temp_dir)

        templates_dir = os.path.join(self.cur_dir, os.path.pardir,
                                     "bin-templates")
        excopy.copy_files_in_dir(
            os.path.join(templates_dir, "cpp-template-default"),
            os.path.join(self.temp_dir, "cpp-template-binary"))
        excopy.copy_files_in_dir(
            os.path.join(templates_dir, "lua-template-runtime"),
            os.path.join(self.temp_dir, "lua-template-binary"))
        excopy.copy_files_in_dir(
            os.path.join(templates_dir, "js-template-runtime"),
            os.path.join(self.temp_dir, "js-template-binary"))
Example #14
0
    def gen_compiled_module(self, module_name):
        print("generate compiled module : %s" % module_name)
        module_info = self.modules_info[module_name]
        # copy the include files
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_INCLUDE):
            for inclue_cfg in module_info[ModuleOrganizer.KEY_MODULE_INCLUDE]:
                excopy.copy_files_with_config(inclue_cfg, self.src_root, self.dst_root)

        # handle the process for android
        self.handle_for_android(module_info)

        # handle the process for win32
        self.handle_for_win32(module_info)

        # handle the process for ios and mac
        self.handle_for_ios_mac(module_info)
Example #15
0
    def gen_compiled_module(self, module_name):
        print("generate compiled module : %s" % module_name)
        module_info = self.modules_info[module_name]
        # copy the include files
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_INCLUDE):
            for inclue_cfg in module_info[ModuleOrganizer.KEY_MODULE_INCLUDE]:
                excopy.copy_files_with_config(inclue_cfg, self.src_root,
                                              self.dst_root)

        # handle the process for android
        self.handle_for_android(module_info)

        # handle the process for win32
        self.handle_for_win32(module_info)

        # handle the process for ios and mac
        self.handle_for_ios_mac(module_info)
Example #16
0
    def record_folder(self, folder):
        if not os.path.isdir(folder):
            return

        if self.dirs is None:
            self.dirs = {}

        if self.dirs.has_key(folder):
            # 已经记录过了,不再重复记录
            return

        # 创建临时文件夹来备份文件
        temp_path = tempfile.mkdtemp()
        copy_cfg = {"from": ".", "to": "."}
        excopy.copy_files_with_config(copy_cfg, folder, temp_path)

        # 记录备份路径
        self.dirs[folder] = temp_path
Example #17
0
    def _modify_libs(self, apk_cfg_info, cfg_dir, rollback_obj):
        #备份res
        rollback_obj.record_folder(
            os.path.join(self.proj_android_path, 'unityLibrary/libs'))
        #应用宝渠道的话需要删除微信sdk
        if apk_cfg_info[PackAPK.CFG_CHANNEL_ID] == "210":
            wx_sdk_file = os.path.join(
                self.proj_android_path,
                'unityLibrary/libs/wechat-sdk-android-without-mta-6.6.4.jar')
            if os.path.exists(wx_sdk_file):
                os.remove(wx_sdk_file)

        for p in apk_cfg_info[PackAPK.CFG_LIBS].split(','):
            libs_path = utils.flat_path(os.path.join(cfg_dir, p.strip()))
            copy_cfg = {'from': '.', 'to': 'libs', 'exclude': ['**/.DS_Store']}
            res_path = utils.flat_path(
                os.path.join(self.proj_android_path, 'unityLibrary'))
            excopy.copy_files_with_config(copy_cfg, libs_path, res_path)
Example #18
0
    def do_build(self):
        #各个游戏,各个渠道
        for game in self.batch_info.keys():
            game = utils.non_unicode_str(game)
            channels = self.batch_info[game]
            for channel_id in channels:
                Logging.debug_msg('----------------' + channel_id)
                try:
                    channel_str = utils.non_unicode_str(channel_id)
                    apk_cfg_file = os.path.join(self.root_dir, game,
                                                channel_str, 'package.json')
                    if not os.path.isfile(apk_cfg_file):
                        Logging.warn_msg('未找到 %s 文件' % apk_cfg_file)
                        return
                    pack_cfg_info = self.parse_json(apk_cfg_file)
                    if pack_cfg_info is None:
                        Logging.warn_msg('解析文件 %s 出错' % apk_cfg_file)
                        return

                    strResPath = utils.non_unicode_str(
                        pack_cfg_info['res_path'])
                    res_path = utils.flat_path(
                        os.path.join(self.root_dir, game, channel_str,
                                     strResPath))

                    strTargetpath = utils.non_unicode_str(
                        pack_cfg_info['target_path'])
                    target_path = utils.flat_path(
                        os.path.join(self.root_dir, strTargetpath))

                    copy_cfg = {
                        'from': '.',
                        'to': '.',
                        'exclude': ['**/.DS_Store']
                    }
                    excopy.copy_files_with_config(copy_cfg, res_path,
                                                  target_path)
                except:
                    Logging.warn_msg('资源拷贝失败')
                finally:
                    Logging.debug_msg('finally :')
                Logging.debug_msg('----------------\n')
Example #19
0
    def copy_files(self, cfg):
        game_pkg_path = self.game_pkg_name.replace('.', '/')
        for item in cfg:
            from_path = utils.flat_path(
                os.path.join(self.proj_path, item['from']))
            to_cfg = item['to']
            to_cfg = to_cfg.replace('$GAME_PKG_NAME', game_pkg_path)
            to_path = utils.flat_path(os.path.join(self.proj_path, to_cfg))

            if from_path == to_path:
                continue

            # 添加条件判断
            if item.has_key('condition'):
                copy_condition = item['condition']
                if not self._check_condition(copy_condition):
                    continue

            copy_cfg = {"from": '.', "to": '.'}
            excopy.copy_files_with_config(copy_cfg, from_path, to_path)
Example #20
0
    def move_files(self, cfg):
        game_pkg_path = self.game_pkg_name.replace('.', '/')
        for item in cfg:
            from_path = utils.flat_path(
                os.path.join(self.proj_path, item['from']))
            to_cfg = item['to']
            to_cfg = to_cfg.replace('$GAME_PKG_NAME', game_pkg_path)
            to_path = utils.flat_path(os.path.join(self.proj_path, to_cfg))

            if from_path == to_path:
                # 源目录和目标目录一致,不需要处理
                continue

            # 拷贝文件/文件夹,然后删除原始文件
            if os.path.isdir(from_path):
                copy_cfg = {"from": '.', "to": '.'}
                excopy.copy_files_with_config(copy_cfg, from_path, to_path)
                shutil.rmtree(from_path)
            elif os.path.isfile(from_path):
                shutil.copy2(from_path, to_path)
                os.remove(from_path)
    def handle_for_lua_bindings(self, module_name):
        module_info = self.modules_info[module_name]
        lua_binding_info = module_info[ModuleOrganizer.KEY_MODULE_LUA_BINDINGS]
        lua_lib_name = lua_binding_info[ModuleOrganizer.KEY_MODULE_LUA_LIB_NAME]
        platforms = {
            "android": "*/%s.a" % lua_lib_name,
            "ios": "%s iOS.a" % lua_lib_name,
            "mac": "%s Mac.a" % lua_lib_name,
            "win32": "%s.lib" % lua_lib_name,
        }

        target_dir = os.path.join(
            self.dst_root, module_info[ModuleOrganizer.KEY_MODULE_TARGET_DIR], "lua-bindings", "prebuilt"
        )
        for p in platforms.keys():
            cpy_info = {"from": p, "to": p, "include": [platforms[p]]}
            excopy.copy_files_with_config(cpy_info, self.prebuilt_dir, target_dir)

        # write the Android.mk for lua-bindings lib
        android_lib_name = lua_binding_info[ModuleOrganizer.KEY_MODULE_ANDROID_LIB_NAME]
        mk_file_path = os.path.join(target_dir, "android", "Android.mk")

        depends = [module_name]
        if lua_binding_info.has_key(ModuleOrganizer.KEY_MODULE_DEPEND_MODULES):
            depends += lua_binding_info[ModuleOrganizer.KEY_MODULE_DEPEND_MODULES]
        whole_libs, call_libs = self.gen_android_depend_str(depends)
        file_content = ModuleOrganizer.MK_FORMAT % (
            android_lib_name,
            lua_lib_name,
            "./$(TARGET_ARCH_ABI)/%s.a" % lua_lib_name,
            "${LOCAL_PATH}/../../include",
            "",
            "",
            "",
            whole_libs,
            call_libs,
        )
        f = open(mk_file_path, "w")
        f.write(file_content)
        f.close()
Example #22
0
    def publish(self, channel, bVconsole):
        print('publish extend')
        sdkPath = ''
        packagePath = channelPath + '/package.json'
        if os.path.exists(packagePath):
            f = open(packagePath)
            package = json.load(f)
            f.close()
            print(package)
            # 添加引用sdk
            if package['sdk']:
                self.copySDK(package['sdk'])
                sdkPath = package['sdk']
        iosPath = utils.flat_path('./local')
        # 同步到publish
        copy_cfg = {'from': '.', 'to': '.', 'exclude': ['**/.DS_Store']}
        # 将构建出来的res、src、subpackages目录拷贝到打包目录
        excopy.copy_files_with_config(copy_cfg, iosPath, publishPath)

        # 给index.html替换时间戳
        self.setGenDate(utils.flat_path(publishPath + '/index.html'), sdkPath,
                        bVconsole)
Example #23
0
    def handle_for_lua_bindings(self, module_name):
        module_info = self.modules_info[module_name]
        lua_binding_info = module_info[ModuleOrganizer.KEY_MODULE_LUA_BINDINGS]
        lua_lib_name = lua_binding_info[
            ModuleOrganizer.KEY_MODULE_LUA_LIB_NAME]
        platforms = {
            "android": "*/%s.a" % lua_lib_name,
            "ios": "%s iOS.a" % lua_lib_name,
            "mac": "%s Mac.a" % lua_lib_name,
            "win32": "%s.lib" % lua_lib_name
        }

        target_dir = os.path.join(
            self.dst_root, module_info[ModuleOrganizer.KEY_MODULE_TARGET_DIR],
            "lua-bindings", "prebuilt")
        for p in platforms.keys():
            cpy_info = {"from": p, "to": p, "include": [platforms[p]]}
            excopy.copy_files_with_config(cpy_info, self.prebuilt_dir,
                                          target_dir)

        # write the Android.mk for lua-bindings lib
        android_lib_name = lua_binding_info[
            ModuleOrganizer.KEY_MODULE_ANDROID_LIB_NAME]
        mk_file_path = os.path.join(target_dir, "android", "Android.mk")

        depends = [module_name]
        if lua_binding_info.has_key(ModuleOrganizer.KEY_MODULE_DEPEND_MODULES):
            depends += lua_binding_info[
                ModuleOrganizer.KEY_MODULE_DEPEND_MODULES]
        whole_libs, call_libs = self.gen_android_depend_str(depends)
        file_content = ModuleOrganizer.MK_FORMAT % \
                     (android_lib_name,
                      lua_lib_name,
                      "./$(TARGET_ARCH_ABI)/%s.a" % lua_lib_name,
                      "${LOCAL_PATH}/../../include",
                      "", "", "", whole_libs, call_libs )
        f = open(mk_file_path, "w")
        f.write(file_content)
        f.close()
Example #24
0
    def gen_prebuilt_module(self, module_name):
        print("generate prebuilt module : %s" % module_name)
        module_info = self.modules_info[module_name]
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_EXCLUDE):
            exclude = module_info[ModuleOrganizer.KEY_MODULE_EXCLUDE]
        else:
            exclude = []

        if module_info.has_key(ModuleOrganizer.KEY_MODULE_INCLUDE):
            include = module_info[ModuleOrganizer.KEY_MODULE_INCLUDE]
        else:
            include = []

        copy_cfg = {
            "from": module_info[ModuleOrganizer.KEY_MODULE_FROM_DIR],
            "to": module_info[ModuleOrganizer.KEY_MODULE_TARGET_DIR]
        }

        if len(include) > 0:
            copy_cfg["include"] = include
        elif len(exclude) > 0:
            copy_cfg["exclude"] = exclude

        excopy.copy_files_with_config(copy_cfg, self.src_root, self.dst_root)
Example #25
0
    def gen_prebuilt_module(self, module_name):
        print("generate prebuilt module : %s" % module_name)
        module_info = self.modules_info[module_name]
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_EXCLUDE):
            exclude = module_info[ModuleOrganizer.KEY_MODULE_EXCLUDE]
        else:
            exclude = []

        if module_info.has_key(ModuleOrganizer.KEY_MODULE_INCLUDE):
            include = module_info[ModuleOrganizer.KEY_MODULE_INCLUDE]
        else:
            include = []

        copy_cfg = {
            "from" : module_info[ModuleOrganizer.KEY_MODULE_FROM_DIR],
            "to": module_info[ModuleOrganizer.KEY_MODULE_TARGET_DIR]
        }

        if len(include) > 0:
            copy_cfg["include"] = include
        elif len(exclude) > 0:
            copy_cfg["exclude"] = exclude

        excopy.copy_files_with_config(copy_cfg, self.src_root, self.dst_root)
Example #26
0
    def do_rollback(self):
        # 先恢复文件夹
        if self.dirs is not None:
            # rollback dirs
            for dir in self.dirs.keys():
                # 先移除现有的文件夹
                if os.path.isdir(dir):
                    shutil.rmtree(dir)
                os.makedirs(dir)

                # 将文件恢复
                copy_cfg = {"from": ".", "to": "."}
                excopy.copy_files_with_config(copy_cfg, self.dirs[dir], dir)

                # 移除临时文件夹
                shutil.rmtree(self.dirs[dir])

            # reset data
            self.dirs = None

        # 再恢复文件
        if self.files is not None:
            # rollback files
            for file_path in self.files.keys():
                dir = os.path.dirname(file_path)
                if not os.path.isdir(dir):
                    os.makedirs(dir)

                target_dir = os.path.dirname(file_path)
                shutil.copy2(self.files[file_path], target_dir)

                # 移除临时文件夹
                shutil.rmtree(os.path.dirname(self.files[file_path]))

            # reset data
            self.files = None
Example #27
0
def do_upgrade(proj_path, src_engine_path, dst_engine_path, ignore_version):
    # print("project path : %s" % proj_path)
    # print("src engine : %s" % src_engine_path)
    # print("dst engine : %s" % dst_engine_path)

    proj_info = ProjectInfo(proj_path)
    # proj_info.print_info()

    # check the project information
    if not proj_info.do_check():
        sys.exit(1)

    # check the engine version
    # 1. The engine version of project should same with the src engine version
    # 2. The src engine version should different with dst engine version
    if not ignore_version:
        # get the engine version of the project
        proj_engine_ver = proj_info.get_engine_version()

        if proj_info.get_language() == 'js':
            engine_version_files = JS_VERSION_FILES
        else:
            engine_version_files = X_VERSION_FILES

        # get the engine version of the src engine
        src_engine_ver = None
        for f in engine_version_files:
            src_full_path = os.path.join(src_engine_path, f)
            if os.path.isfile(src_full_path):
                version = get_engine_version(src_full_path,
                                             proj_info.get_language())
                if version is not None:
                    src_engine_ver = version
                    break
        # print("src engine version : %s" % src_engine_ver)

        # get the engine version of the dst engine
        dst_engine_ver = None
        for f in engine_version_files:
            dst_full_path = os.path.join(dst_engine_path, f)
            if os.path.isfile(dst_full_path):
                version = get_engine_version(dst_full_path,
                                             proj_info.get_language())
                if version is not None:
                    dst_engine_ver = version
                    break
        # print("dst engine version : %s" % dst_engine_ver)

        check_version_ret = True

        # compare the project engine version & src engine version
        if (proj_engine_ver is not None) and (src_engine_ver is not None):
            if proj_engine_ver != src_engine_ver:
                print(
                    "The source engine version '%s' is different with the project engine version '%s'."
                    % (src_engine_ver, proj_engine_ver))
                check_version_ret = False

        # compare the dst engine version & src engine version
        if (dst_engine_ver is not None) and (src_engine_ver is not None):
            if dst_engine_ver == src_engine_ver:
                print(
                    "The source engine version '%s' is same with the destination engine version '%s'."
                    % (src_engine_ver, dst_engine_ver))
                check_version_ret = False

        if not check_version_ret:
            print("\nIf you want to upgrade with:\n"
                  "source engine path: %s\n"
                  "destination engine path: %s\n"
                  "Please add '-i' to ignore the engine version." %
                  (src_engine_path, dst_engine_path))
            sys.exit(1)

    temp_folder = os.path.join(os.path.dirname(proj_path), 'temp')
    try:
        if os.path.exists(temp_folder):
            shutil.rmtree(temp_folder)
    except:
        print("Delete folder %s failed. Please delete/rename it first." %
              temp_folder)
        sys.exit(1)

    work_dir = '%s%s' % (proj_path, UPGRADE_DIR_SUFFIX)
    try:
        if os.path.exists(work_dir):
            shutil.rmtree(work_dir)
    except:
        print("Delete folder %s failed. Please delete/rename it first." %
              work_dir)
        sys.exit(1)

    # create a new project with src engine
    src_cocos = os.path.join(src_engine_path, CONSOLE_PATH)
    new_proj_with_info(proj_info, src_cocos, temp_folder)

    # copy the new project to upgrade folder
    src_empty_proj_path = os.path.join(temp_folder, proj_info.get_proj_name())
    cpy_cfg = {'from': src_empty_proj_path, 'to': work_dir}

    excopy.copy_files_with_config(cpy_cfg, src_empty_proj_path, work_dir)
    if os.path.exists(src_empty_proj_path):
        shutil.rmtree(src_empty_proj_path)

    # get the deleted files
    deleted_files = get_deleted_files(proj_path, work_dir)
    remove_deleted_files(work_dir, deleted_files)

    # init the git repo
    run_shell('git init', cwd=work_dir)
    config_author(work_dir)

    commit_files_with_msg(work_dir, "Init project for cocos upgrade.")

    # new branch for upgrade engine
    cmd = "git checkout -b %s" % UPGRADE_BRANCH_NAME
    run_shell(cmd, cwd=work_dir)

    # remove the files in work dir repo
    remove_dir_except(work_dir, ['.git', '.gitignore'])

    # new project with dst engine
    dst_cocos = os.path.join(dst_engine_path, CONSOLE_PATH)
    new_proj_with_info(proj_info, dst_cocos, temp_folder)

    # copy the dst empty project into work dir
    dst_empty_proj_path = os.path.join(temp_folder, proj_info.get_proj_name())
    cpy_cfg = {'from': dst_empty_proj_path, 'to': work_dir}
    excopy.copy_files_with_config(cpy_cfg, dst_empty_proj_path, work_dir)

    # remove the deleted files
    remove_deleted_files(work_dir, deleted_files)

    # remove the temp dir
    shutil.rmtree(temp_folder, ignore_errors=True)

    # commit files
    commit_files_with_msg(work_dir, "Upgrade engine")

    # checkout master branch
    run_shell('git checkout master', cwd=work_dir)

    # remove files
    remove_dir_except(work_dir, ['.git', '.gitignore'])

    # copy project files to work dir
    cpy_cfg = {'from': proj_path, 'to': work_dir, 'exclude': ['.git']}
    excopy.copy_files_with_config(cpy_cfg, proj_path, work_dir)

    # check if there is any changes
    output = run_shell('git status --porcelain', cwd=work_dir, getOutput=True)
    if (output is not None) and (len(output) > 0):
        # commit files
        commit_files_with_msg(work_dir, "Project development")

    # merge
    has_conflict = False
    try:
        cmd = 'git merge %s' % UPGRADE_BRANCH_NAME
        run_shell(cmd, cwd=work_dir)
    except:
        has_conflict = True
        pass

    if has_conflict:
        try:
            config_merge_tool(work_dir)
            run_shell('git mergetool', cwd=work_dir)
        except:
            print(
                '\nThere are conflicts not resolved. You should solve the conflicts manually.'
            )
            pass
Example #28
0
    def handle_for_android(self, module_info):
        # copy libs file
        android_lib_file_name = module_info[ModuleOrganizer.KEY_MODULE_ANDROID_LIB_FILE_NAME]
        copy_android_lib_cfg = {}
        copy_android_lib_cfg["from"] = "android"
        copy_android_lib_cfg["to"] = "%s/prebuilt/android" % module_info[ModuleOrganizer.KEY_MODULE_TARGET_DIR]
        copy_android_lib_cfg["include"] = [
            "*/%s.a" % android_lib_file_name
        ]
        excopy.copy_files_with_config(copy_android_lib_cfg, self.prebuilt_dir, self.dst_root)

        # generate the prebuilt Android.mk for the module
        android_lib_name = module_info[ModuleOrganizer.KEY_MODULE_ANDROID_LIB_NAME]
        local_src_file = "./$(TARGET_ARCH_ABI)/%s.a" % android_lib_file_name
        export_include_paths = []
        for include_path in module_info[ModuleOrganizer.KEY_MODULE_EXPORT_INCLUDE]:
            temp_path = "${LOCAL_PATH}/%s" % include_path
            export_include_paths.append(temp_path)
        export_include_str = " \\\n".join(export_include_paths)

        export_ldlibs_str = ""
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_EXPORT_LDLIBS):
            export_ldlibs_str = "LOCAL_EXPORT_LDLIBS := "
            for ldlib in module_info[ModuleOrganizer.KEY_MODULE_EXPORT_LDLIBS]:
                export_ldlibs_str += ("-l%s " % ldlib)
            export_ldlibs_str += "\n\n"

        export_cflags_str = ""
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_EXPORT_CFLAGS):
            export_cflags_str = "LOCAL_EXPORT_CFLAGS := "
            export_cflags_str += " ".join(module_info[ModuleOrganizer.KEY_MODULE_EXPORT_CFLAGS])
            export_cflags_str += "\n\n"

        export_cppflags_str = ""
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_EXPORT_CPPFLAGS):
            export_cppflags_str = "LOCAL_EXPORT_CPPFLAGS := "
            export_cppflags_str += " ".join(module_info[ModuleOrganizer.KEY_MODULE_EXPORT_CPPFLAGS])
            export_cppflags_str += "\n\n"

        whole_libs = ""
        call_libs = ""
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_DEPEND_MODULES):
            whole_libs, call_libs = self.gen_android_depend_str(module_info[ModuleOrganizer.KEY_MODULE_DEPEND_MODULES])

        mk_content = ModuleOrganizer.MK_FORMAT % \
                     (android_lib_name,
                      android_lib_file_name,
                      local_src_file,
                      export_include_str,
                      export_ldlibs_str,
                      export_cflags_str,
                      export_cppflags_str,
                      whole_libs,
                      call_libs
                     )

        mk_file_path = os.path.join(self.dst_root, module_info[ModuleOrganizer.KEY_MODULE_TARGET_DIR], "prebuilt/android/Android.mk")
        mk_dir = os.path.dirname(mk_file_path)
        if not os.path.exists(mk_dir):
            os.makedirs(mk_dir)
        mk_obj = open(mk_file_path, "w")
        mk_obj.write(mk_content)
        mk_obj.close()
Example #29
0
    def build_one_apk(self, app_id, channel_id, rollback_obj):
        apk_cfg_file = os.path.join(self.root_dir, app_id, channel_id,
                                    'package.json')
        if not os.path.isfile(apk_cfg_file):
            Logging.warn_msg('未找到 %s 文件,打包失败' % apk_cfg_file)
            return

        Logging.debug_msg('开始使用配置文件 %s 打包' % apk_cfg_file)
        apk_cfg_info = self._parse_json(apk_cfg_file)
        if apk_cfg_info is None:
            Logging.warn_msg('解析文件 %s 出错,打包失败' % apk_cfg_file)
            return

        cfg_dir = os.path.dirname(apk_cfg_file)

        check_gt_ret = self._check_gt_info(apk_cfg_info, cfg_dir)
        if check_gt_ret:
            Logging.warn_msg(check_gt_ret + ', 打包失败')
            return

        check_ret = self._check_cfg_info(apk_cfg_info, cfg_dir)
        if check_ret:
            Logging.warn_msg(check_ret + ',打包失败')
            return

        # 备份文件和文件夹
        rollback_obj.record_file(utils.flat_path(self.library_manifest))
        rollback_obj.record_file(utils.flat_path(self.manifest))
        rollback_obj.record_folder(os.path.join(self.proj_android_path, 'res'))

        game_name = utils.non_unicode_str(apk_cfg_info[PackAPK.CFG_GAME_NAME])
        pkg_name = utils.non_unicode_str(apk_cfg_info[PackAPK.CFG_PKG_NAME])
        gaode_key = utils.non_unicode_str(apk_cfg_info[PackAPK.CFG_GAODE_KEY])
        ver_name = utils.non_unicode_str(
            apk_cfg_info[PackAPK.CFG_VERSION_NAME])
        ver_code = utils.non_unicode_str(
            apk_cfg_info[PackAPK.CFG_VERSION_CODE])
        app_scheme = utils.non_unicode_str(
            apk_cfg_info[PackAPK.CFG_APP_SCHEME])
        need_remove_agora = True  # Android 去掉视频 SDK apk_cfg_info.get(PackAPK.CFG_NO_AGORA, False)

        # 修改 java 文件中 R 的包名
        self._modify_java_files(pkg_name, rollback_obj)

        # 对需要修改包名的文件进行包名替换
        self._change_pkg_name(pkg_name, rollback_obj)

        # 修改 bugly appid
        if apk_cfg_info.has_key(PackAPK.CFG_BUGLY_ID):
            bugly_appid = utils.non_unicode_str(
                apk_cfg_info[PackAPK.CFG_BUGLY_ID])
        else:
            bugly_appid = ""
        if len(bugly_appid) > 0:
            self._modify_bugly(self.library_manifest, bugly_appid, channel_id)

        # 修改高德 key
        if len(gaode_key) > 0:
            self._modify_gaode_key(self.library_manifest, gaode_key)

        # 修改 Agora id
        if apk_cfg_info.has_key(PackAPK.CFG_AGORA_ID):
            self._modify_agora_id(self.library_manifest,
                                  apk_cfg_info[PackAPK.CFG_AGORA_ID])

        # 修改 AndroidManifest.xml
        self._modify_manifest(pkg_name, ver_name, ver_code)

        # 替换 java res
        for p in apk_cfg_info[PackAPK.CFG_JAVA_RES].split(','):
            java_res_path = utils.flat_path(os.path.join(cfg_dir, p.strip()))
            copy_cfg = {'from': '.', 'to': 'res', 'exclude': ['**/.DS_Store']}
            excopy.copy_files_with_config(copy_cfg, java_res_path,
                                          self.proj_android_path)

        # 替换 个推通知图标push.png
        # isTurnOffPush = apk_cfg_info.get(PackAPK.CFG_TURNOFF_PUSH, None)
        # if isTurnOffPush != "1":
        push_res_path = utils.flat_path(os.path.join(cfg_dir, "../pushRes"))
        proj_getui_path = utils.flat_path(
            os.path.join(self.proj_android_path,
                         '../library.pushgetui.android'))
        if not os.path.isdir(proj_getui_path):
            raise_known_error("未找到 getui 工程文件夹 %s" % proj_getui_path)
        copy_cfg = {'from': '.', 'to': 'res', 'exclude': ['**/.DS_Store']}
        rollback_obj.record_folder(os.path.join(proj_getui_path, "res"))
        if os.path.isdir(push_res_path):
            excopy.copy_files_with_config(copy_cfg, push_res_path,
                                          proj_getui_path)
        else:
            # raise_known_error('文件夹 %s 不存在,放置个推通知图标pushRes/drawable-xxhdpi/push.png|push_small.png' % push_res_path, KnownError.ERROR_PATH_NOT_FOUND)
            res_path = utils.flat_path(
                os.path.join(self.proj_android_path, "res"))
            pushSmallSrc_path = utils.flat_path(
                os.path.join(res_path, "mipmap-hdpi/ic_launcher.png"))
            pushSrc_path = utils.flat_path(
                os.path.join(res_path, "mipmap-xxxhdpi/ic_launcher.png"))
            pushDes_path = utils.flat_path(
                os.path.join(proj_getui_path, "res/drawable-xxhdpi/push.png"))
            pushSmallDes_path = utils.flat_path(
                os.path.join(proj_getui_path,
                             "res/drawable-xxhdpi/push_small.png"))
            # excopy.copy_files_with_config(copy_cfg, push_res_path, proj_getui_path)
            shutil.copyfile(pushSrc_path, pushDes_path)
            shutil.copyfile(pushSmallSrc_path, pushSmallDes_path)

        Logging.debug_msg('个推通知图标替换完成')

        # 修改 strings.xml
        self._modify_strings_xml(game_name, app_scheme)

        # 获取并清理临时的 assets 文件夹
        temp_assets_path = os.path.join(self.temp_dir,
                                        '%s_%s_assets' % (app_id, channel_id))
        if os.path.isdir(temp_assets_path):
            shutil.rmtree(temp_assets_path)

        Logging.debug_msg('开始处理资源文件')

        # 拷贝大厅的资源文件
        for p in PackAPK.DEFAULT_HALL_DIRS:
            copy_cfg = {
                'from': p,
                'to': p,
                'exclude': ['**/.DS_Store', 'LuaDebugjit.lua']
            }
            excopy.copy_files_with_config(copy_cfg, self.res_root_path,
                                          temp_assets_path)

        # 拷贝游戏通用组件的各个部分
        game_common_parts = apk_cfg_info.get(PackAPK.CFG_GAME_COMMON_PARTS,
                                             None)
        self._copy_game_common_parts(game_common_parts, temp_assets_path)

        # 拷贝指定的游戏文件
        games_dirs = []
        games = apk_cfg_info.get(PackAPK.CFG_GAMES, None)
        if isinstance(games, list) and len(games) > 0:
            games_dirs.extend(games)

        if len(games_dirs) > 0:
            if not os.path.isdir(self.games_root_path):
                raise_known_error('文件夹 %s 不存在' % self.games_root_path,
                                  KnownError.ERROR_PATH_NOT_FOUND)

            for game in games_dirs:
                copy_cfg = {
                    'from': '%s' % game,
                    'to': 'games/%s' % game,
                    'exclude': ['**/.DS_Store', '*.git']
                }
                excopy.copy_files_with_config(copy_cfg, self.games_root_path,
                                              temp_assets_path)

        # 替换游戏配置文件
        for p in apk_cfg_info[PackAPK.CFG_FILES].split(','):
            cfg_path = utils.flat_path(os.path.join(cfg_dir, p.strip()))
            copy_cfg = {'from': '.', 'to': 'src', 'exclude': ['**/.DS_Store']}
            excopy.copy_files_with_config(copy_cfg, cfg_path, temp_assets_path)

        # cfg_package.lua文件末尾写入打包文件夹名称时间戳
        tmpFile = open(os.path.join(temp_assets_path, "src/cfg_package.lua"),
                       'a')
        tmpFile.write('\nPACKAGE_TIMESTAMP=' + '\"' + self.packageTimestamp +
                      '\"')
        tmpFile.close()

        # 替换 res 文件夹
        if apk_cfg_info.has_key(PackAPK.CFG_RES_FILES):
            for p in apk_cfg_info[PackAPK.CFG_RES_FILES].split(','):
                res_path = utils.flat_path(os.path.join(cfg_dir, p.strip()))
                copy_cfg = {
                    'from': '.',
                    'to': 'res',
                    'exclude': ['**/.DS_Store']
                }
                excopy.copy_files_with_config(copy_cfg, res_path,
                                              temp_assets_path)

        # 删除不需要的品牌资源文件夹
        for brand in utils.get_support_brands():
            brand_path = utils.flat_path(
                os.path.join(temp_assets_path, 'res', brand))
            if brand != self.brand and os.path.isdir(brand_path):
                shutil.rmtree(brand_path)

        # 删除不属于该地区的地图资源文件
        if apk_cfg_info.has_key(PackAPK.CFG_REGION) and apk_cfg_info[
                PackAPK.CFG_REGION] != 'all':
            region_list = []
            new_list = apk_cfg_info[PackAPK.CFG_REGION].split(',')
            for r in new_list:
                if r.strip() != '':
                    region_list.append(r)

            # 超过1个地区时需要带上全国地图
            if len(region_list) > 1:
                region_list.append('0')

            keep_name_list = []
            for region in region_list:
                keep_name = 'map_%s' % region
                keep_name_list.append(keep_name)

            map_path = utils.flat_path(
                os.path.join(temp_assets_path, 'res/hall/map'))
            if os.path.isdir(map_path):
                for f in os.listdir(map_path):
                    full_path = os.path.join(map_path, f)
                    if f not in keep_name_list and os.path.isdir(full_path):
                        shutil.rmtree(full_path)

                # 如果不显示全国地图,则删除云动画的图片
                if len(region_list) <= 1:
                    cloud1_path = os.path.join(map_path, "yun1.png")
                    cloud2_path = os.path.join(map_path, "yun2.png")
                    os.remove(cloud1_path)
                    os.remove(cloud2_path)

        # 清理 assets 文件夹,只保留需要的文件
        assets_path = os.path.join(self.proj_android_path, 'assets')
        file_recorder = utils.FileRollback()
        for f in PackAPK.NEED_BACKUP_ASSETS:
            file_recorder.record_file(
                utils.flat_path(os.path.join(assets_path, f)))
        if os.path.isdir(assets_path):
            shutil.rmtree(assets_path)
        if not self.no_rollback:
            file_recorder.do_rollback()

        # 进行加密或者直接拷贝资源文件
        if os.path.isdir(temp_assets_path):
            # 生成 native 环境信息文件
            params = None
            if need_remove_agora:
                # 需要移除 agora
                params = {"no_agora": "true"}
            utils.write_native_info(
                os.path.join(temp_assets_path, 'src/NativeInfo.lua'), params)
            if not self.no_encrypt:
                self._do_encrypt(temp_assets_path, assets_path)
            else:
                copy_cfg = {
                    'from': '.',
                    'to': '.',
                    'exclude': ['**/.DS_Store']
                }
                excopy.copy_files_with_config(copy_cfg, temp_assets_path,
                                              assets_path)
                f = open(os.path.join(assets_path, 'src/myflag'), 'w')
                f.write('')
                f.close()

        Logging.debug_msg('资源文件处理结束')

        # 处理 SDK 相关的配置
        Logging.debug_msg('处理 SDK 相关的配置开始')
        sdks_cfg = apk_cfg_info.get(PackAPK.CFG_SDKS, {})
        remove_weixin = apk_cfg_info.get(PackAPK.CFG_REMOVE_WEIXIN, False)
        remove_youqu = apk_cfg_info.get(PackAPK.CFG_REMOVE_YOUQU, False)
        sdk_mgr = SDKManager.SDKManager(rollback_obj, pkg_name, sdks_cfg,
                                        remove_weixin, remove_youqu,
                                        self.build_gradle,
                                        self.proj_android_path,
                                        self.proj_androidStudio_path)
        sdk_mgr.prepare_sdk()
        Logging.debug_msg('处理 SDK 相关的配置结束')

        # 检查是否需要删除 agora 的库文件
        if need_remove_agora:
            self._do_remove_agora(rollback_obj)

        # 最终 apk 文件名格式为:GAMENAME_PKGNAME_APPID_CHANNELID_VERNAME_VERCODE.apk
        Logging.debug_msg('生成apk文件名')
        name_infos = [pkg_name, app_id, channel_id, ver_name, ver_code]
        remark = utils.non_unicode_str(apk_cfg_info.get(
            PackAPK.CFG_REMARK, ""))
        if len(remark) is not 0:
            name_infos.append(remark)

        if self.no_encrypt:
            name_infos.append('NO_ENCRYPT')

        # 是否删除 agora
        # if need_remove_agora:
        #     name_infos.append("NO_AGORA")

        # 文件名增加时间戳
        Logging.debug_msg('文件名增加时间戳')
        cur_time_str = datetime.datetime.fromtimestamp(
            time.time()).strftime('%Y%m%d_%H%M%S')
        name_infos.append(cur_time_str)

        apk_name = '_'.join(name_infos) + '.apk'
        out_file_path = os.path.join(self.output_path, apk_name)
        if not os.path.isdir(self.output_path):
            os.makedirs(self.output_path)

        if self.build_gradle:
            # 进行 gradle 打包
            Logging.debug_msg('进行 gradle 打包')
            try:
                self.build_apk_gradle(rollback_obj, cfg_dir, apk_cfg_info,
                                      apk_name)
                self.build_result['%s_%s' %
                                  (app_id, channel_id)] = out_file_path
            except:
                print 'traceback.format_exc():\n%s' % traceback.format_exc()
                return
        else:
            # 进行 ant 打包
            Logging.debug_msg('进行 ant 打包')
            keystore_path = utils.flat_path(
                os.path.join(
                    cfg_dir,
                    apk_cfg_info[PackAPK.CFG_SIGN][PackAPK.CFG_SIGN_FILE]))
            keystore_pass = apk_cfg_info[PackAPK.CFG_SIGN][
                PackAPK.CFG_SIGN_PASSWORD]
            alias = apk_cfg_info[PackAPK.CFG_SIGN][PackAPK.CFG_SIGN_ALIAS]
            alias_pass = apk_cfg_info[PackAPK.CFG_SIGN][
                PackAPK.CFG_SIGN_ALIAS_PASSWORD]
            ant_cmd = PackAPK.ANT_CMD_FMT % (self.ant_bin, self.build_xml,
                                             self.sdk_root, keystore_path,
                                             alias, keystore_pass, alias_pass)
            try:
                utils.run_shell(ant_cmd)
            except:
                Logging.warn_msg('打包失败')
                return
            # 将 apk 包拷贝到指定位置
            build_path = utils.flat_path(
                os.path.join(self.proj_android_path,
                             'bin/%s-release.apk' % self.proj_name))
            shutil.copy(utils.get_sys_encode_str(build_path),
                        utils.get_sys_encode_str(out_file_path))
            Logging.debug_msg('生成的 apk 文件路径:%s' % out_file_path)
            self.build_result['%s_%s' % (app_id, channel_id)] = out_file_path
        try:
            shutil.rmtree(temp_assets_path)
        except:
            pass
Example #30
0
    def do_build(self):
        print("Source Path : %s" % self.src_path)
        print("Output Path : %s" % self.dst_path)
        print("Start building")

        if os.path.exists(self.dst_path):
            shutil.rmtree(self.dst_path)

        # copy files
        copy_config = self.cfg_info[Builder.KEY_COPY_CONFIG]
        copy_cfgs = copy_config["common"]
        if sys.platform in copy_config:
            copy_cfgs += copy_config[sys.platform]
        elif os_is_linux():
            copy_cfgs += copy_config["linux"]

        for element in copy_cfgs:
            excopy.copy_files_with_config(element, self.src_path, self.dst_path)

        # modify files
        modify_config = self.cfg_info[Builder.KEY_MODIFY_CONFIG]
        for element in modify_config:
            self.modify_files(element)

        # get the path parameter
        plugins_path = os.path.join(self.src_path, "plugins")
        bin_path = os.path.join(self.src_path, "bin")
        dir_list = self._get_dirs(plugins_path)
        dir_list.append(plugins_path)
        dir_list.append(bin_path)
        dir_list.append(self.src_path)

        if os_is_win32():
            sep = ";"
        else:
            sep = ":"
        path_param = "-p %s" % sep.join(dir_list)

        # get the runtime-hook parameter
        _cp = ConfigParser.ConfigParser(allow_no_value=True)
        _cp.optionxform = str
        _cp.read(os.path.join(self.src_path, "bin/cocos2d.ini"))

        runtime_hook_param = ""
        hidden_import_param = ""

        # add hidden import params for config.json
        if self.cfg_info.has_key(Builder.KEY_HIDDEN_IMPORT):
            hidden_import_cfg = self.cfg_info[Builder.KEY_HIDDEN_IMPORT]
        else:
            hidden_import_cfg = {}

        if len(hidden_import_cfg) > 0:
            for key in hidden_import_cfg:
                hidden_import_param += "--hidden-import %s " % key
                runtime_hook_param += '--runtime-hook "%s" ' % os.path.join(self.src_path, hidden_import_cfg[key])

        for s in _cp.sections():
            if s == 'plugins':
                for classname in _cp.options(s):
                    parts = classname.split(".")
                    module_name = parts[0]
                    hidden_import_param += "--hidden-import %s " % module_name

                    module_path = os.path.join(plugins_path, module_name)
                    if os.path.isdir(module_path):
                        runtime_hook_param += '--runtime-hook "%s" ' % ("%s/__init__.py" % module_path)
                    else:
                        module_file = "%s.py" % module_path
                        if os.path.isfile(module_file):
                            runtime_hook_param += '--runtime-hook "%s" ' % module_file

        # additional hooks path
        add_hook_dir_param = '--additional-hooks-dir "%s" ' % plugins_path
        add_hook_dir_param += '--additional-hooks-dir "%s" ' % bin_path
        add_hook_dir_param += '--additional-hooks-dir "%s"' % self.src_path

        # build *.py
        if os_is_linux():
            spec_path = os.path.join(self.my_path, "build", "linux")
        else:
            spec_path = os.path.join(self.my_path, "build", sys.platform)
        work_path = spec_path
        if os.path.exists(spec_path):
            shutil.rmtree(spec_path)
        build_cmd = Builder.CMD_FORMAT % (path_param, '%s %s %s' % (hidden_import_param, add_hook_dir_param, runtime_hook_param), self.dst_path, spec_path, work_path, self.entrance_file)
        run_shell(build_cmd)

        print("Building succeed.")
Example #31
0
def do_upgrade(proj_path, src_engine_path, dst_engine_path, ignore_version):
    # print("project path : %s" % proj_path)
    # print("src engine : %s" % src_engine_path)
    # print("dst engine : %s" % dst_engine_path)

    proj_info = ProjectInfo(proj_path)
    # proj_info.print_info()

    # check the project information
    if not proj_info.do_check():
        sys.exit(1)

    # check the engine version
    # 1. The engine version of project should same with the src engine version
    # 2. The src engine version should different with dst engine version
    if not ignore_version:
        # get the engine version of the project
        proj_engine_ver = proj_info.get_engine_version()

        if proj_info.get_language() == 'js':
            engine_version_files = JS_VERSION_FILES
        else:
            engine_version_files = X_VERSION_FILES

        # get the engine version of the src engine
        src_engine_ver = None
        for f in engine_version_files:
            src_full_path = os.path.join(src_engine_path, f)
            if os.path.isfile(src_full_path):
                version = get_engine_version(src_full_path, proj_info.get_language())
                if version is not None:
                    src_engine_ver = version
                    break
        # print("src engine version : %s" % src_engine_ver)

        # get the engine version of the dst engine
        dst_engine_ver = None
        for f in engine_version_files:
            dst_full_path = os.path.join(dst_engine_path, f)
            if os.path.isfile(dst_full_path):
                version = get_engine_version(dst_full_path, proj_info.get_language())
                if version is not None:
                    dst_engine_ver = version
                    break
        # print("dst engine version : %s" % dst_engine_ver)

        check_version_ret = True

        # compare the project engine version & src engine version
        if (proj_engine_ver is not None) and (src_engine_ver is not None):
            if proj_engine_ver != src_engine_ver:
                print("The source engine version '%s' is different with the project engine version '%s'."
                      % (src_engine_ver, proj_engine_ver))
                check_version_ret = False

        # compare the dst engine version & src engine version
        if (dst_engine_ver is not None) and (src_engine_ver is not None):
            if dst_engine_ver == src_engine_ver:
                print("The source engine version '%s' is same with the destination engine version '%s'."
                      % (src_engine_ver, dst_engine_ver))
                check_version_ret = False

        if not check_version_ret:
            print("\nIf you want to upgrade with:\n"
                  "source engine path: %s\n"
                  "destination engine path: %s\n"
                  "Please add '-i' to ignore the engine version."
                  % (src_engine_path, dst_engine_path))
            sys.exit(1)

    temp_folder = os.path.join(os.path.dirname(proj_path), 'temp')
    try:
        if os.path.exists(temp_folder):
            shutil.rmtree(temp_folder)
    except:
        print("Delete folder %s failed. Please delete/rename it first." % temp_folder)
        sys.exit(1)

    work_dir = '%s%s' % (proj_path, UPGRADE_DIR_SUFFIX)
    try:
        if os.path.exists(work_dir):
            shutil.rmtree(work_dir)
    except:
        print("Delete folder %s failed. Please delete/rename it first." % work_dir)
        sys.exit(1)

    # create a new project with src engine
    src_cocos = os.path.join(src_engine_path, CONSOLE_PATH)
    new_proj_with_info(proj_info, src_cocos, temp_folder)

    # copy the new project to upgrade folder
    src_empty_proj_path = os.path.join(temp_folder, proj_info.get_proj_name())
    cpy_cfg = {
        'from' : src_empty_proj_path,
        'to' : work_dir
    }

    excopy.copy_files_with_config(cpy_cfg, src_empty_proj_path, work_dir)
    if os.path.exists(src_empty_proj_path):
        shutil.rmtree(src_empty_proj_path)

    # get the deleted files
    deleted_files = get_deleted_files(proj_path, work_dir)
    remove_deleted_files(work_dir, deleted_files)

    # init the git repo
    run_shell('git init', cwd=work_dir)
    config_author(work_dir)

    commit_files_with_msg(work_dir, "Init project for cocos upgrade.")

    # new branch for upgrade engine
    cmd = "git checkout -b %s" % UPGRADE_BRANCH_NAME
    run_shell(cmd, cwd=work_dir)

    # remove the files in work dir repo
    remove_dir_except(work_dir, [ '.git', '.gitignore'] )

    # new project with dst engine
    dst_cocos = os.path.join(dst_engine_path, CONSOLE_PATH)
    new_proj_with_info(proj_info, dst_cocos, temp_folder)

    # copy the dst empty project into work dir
    dst_empty_proj_path = os.path.join(temp_folder, proj_info.get_proj_name())
    cpy_cfg = {
        'from' : dst_empty_proj_path,
        'to' : work_dir
    }
    excopy.copy_files_with_config(cpy_cfg, dst_empty_proj_path, work_dir)

    # remove the deleted files
    remove_deleted_files(work_dir, deleted_files)

    # remove the temp dir
    shutil.rmtree(temp_folder, ignore_errors=True)

    # commit files
    commit_files_with_msg(work_dir, "Upgrade engine")

    # checkout master branch
    run_shell('git checkout master', cwd=work_dir)

    # remove files
    remove_dir_except(work_dir, [ '.git', '.gitignore' ] )

    # copy project files to work dir
    cpy_cfg = {
        'from' : proj_path,
        'to' : work_dir,
        'exclude' : [
            '.git'
        ]
    }
    excopy.copy_files_with_config(cpy_cfg, proj_path, work_dir)

    # commit files
    commit_files_with_msg(work_dir, "Project development")

    # merge
    has_conflict = False
    try:
        cmd = 'git merge %s' % UPGRADE_BRANCH_NAME
        run_shell(cmd, cwd=work_dir)
    except:
        has_conflict = True
        pass

    if has_conflict:
        try:
            config_merge_tool(work_dir)
            run_shell('git mergetool', cwd=work_dir)
        except:
            print('\nThere are conflicts not resolved. You should solve the conflicts manually.')
            pass
Example #32
0
def do_upgrade(proj_path, src_engine_path, dst_engine_path):
    # print("project path : %s" % proj_path)
    # print("src engine : %s" % src_engine_path)
    # print("dst engine : %s" % dst_engine_path)

    proj_info = ProjectInfo(proj_path)
    # print("project name : %s" % proj_info.get_proj_name())
    # print("language : %s" % proj_info.get_language())
    # print("package name : %s" % proj_info.get_pkg_name())
    # print("is runtime : %s" % proj_info.is_runtime_proj())
    # print("ios bundle id : %s" % proj_info.get_ios_bundleid())
    # print("mac bundle id : %s" % proj_info.get_mac_bundleid())

    # TODO check the project info

    temp_folder = os.path.join(os.path.dirname(proj_path), 'temp')

    if os.path.exists(temp_folder):
        shutil.rmtree(temp_folder)

    # create a new project with src engine
    src_cocos = os.path.join(src_engine_path, CONSOLE_PATH)
    new_proj_with_info(proj_info, src_cocos, temp_folder)

    # copy the new project to upgrade folder
    work_dir = '%s%s' % (proj_path, UPGRADE_DIR_SUFFIX)
    src_empty_proj_path = os.path.join(temp_folder, proj_info.get_proj_name())
    cpy_cfg = {
        'from' : src_empty_proj_path,
        'to' : work_dir
    }
    if os.path.exists(work_dir):
        shutil.rmtree(work_dir)
    excopy.copy_files_with_config(cpy_cfg, src_empty_proj_path, work_dir)
    if os.path.exists(src_empty_proj_path):
        shutil.rmtree(src_empty_proj_path)

    # get the deleted files
    deleted_files = get_deleted_files(proj_path, work_dir)
    remove_deleted_files(work_dir, deleted_files)

    # init the git repo
    run_shell('git init', cwd=work_dir)
    config_author(work_dir)

    commit_files_with_msg(work_dir, "Init project for cocos upgrade.")

    # new branch for upgrade engine
    cmd = "git checkout -b %s" % UPGRADE_BRANCH_NAME
    run_shell(cmd, cwd=work_dir)

    # remove the files in work dir repo
    remove_dir_except(work_dir, [ '.git', '.gitignore'] )

    # new project with dst engine
    dst_cocos = os.path.join(dst_engine_path, CONSOLE_PATH)
    new_proj_with_info(proj_info, dst_cocos, temp_folder)

    # copy the dst empty project into work dir
    dst_empty_proj_path = os.path.join(temp_folder, proj_info.get_proj_name())
    cpy_cfg = {
        'from' : dst_empty_proj_path,
        'to' : work_dir
    }
    excopy.copy_files_with_config(cpy_cfg, dst_empty_proj_path, work_dir)

    # remove the deleted files
    remove_deleted_files(work_dir, deleted_files)

    # remove the temp dir
    shutil.rmtree(temp_folder, ignore_errors=True)

    # commit files
    commit_files_with_msg(work_dir, "Upgrade engine")

    # checkout master branch
    run_shell('git checkout master', cwd=work_dir)

    # remove files
    remove_dir_except(work_dir, [ '.git', '.gitignore' ] )

    # copy project files to work dir
    cpy_cfg = {
        'from' : proj_path,
        'to' : work_dir,
        'exclude' : [
            '.git'
        ]
    }
    excopy.copy_files_with_config(cpy_cfg, proj_path, work_dir)

    # commit files
    commit_files_with_msg(work_dir, "Project development")

    # merge
    has_conflict = False
    try:
        cmd = 'git merge %s' % UPGRADE_BRANCH_NAME
        run_shell(cmd, cwd=work_dir)
    except:
        has_conflict = True
        pass

    if has_conflict:
        try:
            config_merge_tool(work_dir)
            run_shell('git mergetool', cwd=work_dir)
        except:
            print('\nThere are conflicts not resolved. You should solve the conflicts manually.')
            pass
Example #33
0
def createZip(zipDir, dst, versionName):
    tempPath = utils.flat_path(os.path.join(dst, "../temp"))
    publishPath = utils.flat_path(os.path.join(dst, "../publish"))
    print(tempPath)
    print(publishPath)
    #拷贝主包的资源生成为更新包
    if os.path.isdir(tempPath):
        time.sleep(0.01)
        shutil.rmtree(tempPath)
        time.sleep(0.01)
    #src目录
    mainPackageCfg = {
        'from': 'mainPackage/src',
        'to': 'src',
        'exclude': [
            '**/.DS_Store',
            '**/manifest.*',
        ]
    }
    excopy.copy_files_with_config(mainPackageCfg, dst, tempPath)
    #res目录
    mainPackageCfg = {
        'from': 'mainPackage/res',
        'to': 'res',
        'exclude': [
            '**/.DS_Store',
        ]
    }
    excopy.copy_files_with_config(mainPackageCfg, dst, tempPath)

    manifest = {}
    manifest["version"] = versionName
    manifest["packageUrl"] = ''
    manifest["remoteManifestUrl"] = ''
    manifest["remoteVersionUrl"] = ''
    manifest["searchPaths"] = []
    manifest["assets"] = {}

    assets = manifest["assets"]
    get_file_path_md5(tempPath, '/src', assets)
    get_file_path_md5(tempPath, '/res', assets)

    #创建project.manifest
    project_manifest = utils.flat_path(
        os.path.join(tempPath, 'project.manifest'))
    file_m = open(project_manifest, "wb")
    file_m.writelines(json.dumps(manifest))
    file_m.close()

    #创建version.manifest
    manifest["assets"] = {}
    version_manifest = utils.flat_path(
        os.path.join(tempPath, 'version.manifest'))
    file_m = open(version_manifest, "wb")
    file_m.writelines(json.dumps(manifest))
    file_m.close()

    #拷贝exclude目录
    if bExclude:
        excludePath = dst + '/exclude'
        for (parent, dirs, files) in os.walk(excludePath):
            for f in files:
                if f == '.DS_Store':
                    continue
                full_path = os.path.join(parent, f)
                rel_path = os.path.relpath(full_path, excludePath)
                rel_path = rel_path.replace('\\', '/')
                #print(rel_path)
                moveFileTo(full_path, tempPath + '/' + rel_path)
    if zipDir == '':
        zipDir = 'creator'
    #生成zip包
    out_dir = '%s/%s/%s.zip' % (publishPath, zipDir, versionName)
    utils.zip_folder(tempPath, out_dir)
 def copy_template(self):
     for item in self.config_json[CocosBinTemplateGenerator.KEY_COPY_CONFIG]:
         excopy.copy_files_with_config(item, self.repo_x, self.engine_template_dir)
Example #35
0
    def compile_android(self):
        print("compile android")
        # build .so for android
        CONSOLE_PATH = "tools/cocos2d-console/bin"
        ANDROID_A_PATH = "frameworks/runtime-src/proj.android/obj/local"

        android_out_dir = os.path.join(self.lib_dir, "android")
        engine_dir = self.repo_x
        console_dir = os.path.join(engine_dir, CONSOLE_PATH)
        if utils_cocos.os_is_win32():
            cmd_path = os.path.join(console_dir, "cocos.bat")
        else:
            cmd_path = os.path.join(console_dir, "cocos")

        # build the simulator project
        proj_path = os.path.join(engine_dir, 'tools/simulator')
        build_cmd = "%s compile -s %s -p android --ndk-mode release --app-abi %s" % (cmd_path, proj_path, self.app_abi)
        utils_cocos.execute_command(build_cmd)

        # copy .a to prebuilt dir
        obj_dir = os.path.join(proj_path, ANDROID_A_PATH)
        copy_cfg = {
            "from": obj_dir,
            "to": android_out_dir,
            "include": [
                "*.a$"
            ]
        }
        excopy.copy_files_with_config(copy_cfg, obj_dir, android_out_dir)

        if not self.disable_strip:
            # strip the android libs
            ndk_root = os.environ["NDK_ROOT"]
            if utils_cocos.os_is_win32():
                if utils_cocos.is_32bit_windows():
                    bit_str = ""
                else:
                    bit_str = "-x86_64"
                sys_folder_name = "windows%s" % bit_str
            elif utils_cocos.os_is_mac():
                sys_folder_name = "darwin-x86_64"

            # set strip execute file name
            if utils_cocos.os_is_win32():
                strip_execute_name = "strip.exe"
            else:
                strip_execute_name = "strip"

            # strip arm libs
            strip_cmd_path = os.path.join(ndk_root, "toolchains/arm-linux-androideabi-4.8/prebuilt/%s/arm-linux-androideabi/bin/%s"
                % (sys_folder_name, strip_execute_name))
            if not os.path.exists(strip_cmd_path):
                strip_cmd_path = os.path.join(ndk_root, "toolchains/arm-linux-androideabi-4.8/prebuilt/%s/arm-linux-androideabi/bin/%s"
                    % (sys_folder_name.replace(bit_str, ""), strip_execute_name))
            if os.path.exists(strip_cmd_path):
                armlibs = ["armeabi", "armeabi-v7a"]
                for fold in armlibs:
                    self.trip_libs(strip_cmd_path, os.path.join(android_out_dir, fold))

            # strip x86 libs
            strip_cmd_path = os.path.join(ndk_root, "toolchains/x86-4.8/prebuilt/%s/i686-linux-android/bin/%s" % (sys_folder_name, strip_execute_name))
            if os.path.exists(strip_cmd_path) and os.path.exists(os.path.join(android_out_dir, "x86")):
                self.trip_libs(strip_cmd_path, os.path.join(android_out_dir, 'x86'))
 def copy_files(self):
     for cfg in self.copy_cfg:
         excopy.copy_files_with_config(cfg, self.root_dir, self.root_dir)
Example #37
0
    def compile_android(self):
        print("compile android")
        # build .so for android
        CONSOLE_PATH = "tools/cocos2d-console/bin"
        ANDROID_A_PATH = "frameworks/runtime-src/proj.android/obj/local"

        android_out_dir = os.path.join(self.lib_dir, "android")
        engine_dir = self.repo_x
        console_dir = os.path.join(engine_dir, CONSOLE_PATH)
        if utils_cocos.os_is_win32():
            cmd_path = os.path.join(console_dir, "cocos.bat")
        else:
            cmd_path = os.path.join(console_dir, "cocos")

        # build the simulator project
        proj_path = os.path.join(engine_dir, 'tools/simulator')
        build_cmd = "%s compile -s %s -p android --ndk-mode release --app-abi %s" % (
            cmd_path, proj_path, self.app_abi)
        utils_cocos.execute_command(build_cmd)

        # copy .a to prebuilt dir
        obj_dir = os.path.join(proj_path, ANDROID_A_PATH)
        copy_cfg = {
            "from": obj_dir,
            "to": android_out_dir,
            "include": ["*.a$"]
        }
        excopy.copy_files_with_config(copy_cfg, obj_dir, android_out_dir)

        if not self.disable_strip:
            # strip the android libs
            ndk_root = os.environ["NDK_ROOT"]
            if utils_cocos.os_is_win32():
                if utils_cocos.is_32bit_windows():
                    bit_str = ""
                else:
                    bit_str = "-x86_64"
                sys_folder_name = "windows%s" % bit_str
            elif utils_cocos.os_is_mac():
                sys_folder_name = "darwin-x86_64"

            # set strip execute file name
            if utils_cocos.os_is_win32():
                strip_execute_name = "strip.exe"
            else:
                strip_execute_name = "strip"

            # strip arm libs
            strip_cmd_path = os.path.join(
                ndk_root,
                "toolchains/arm-linux-androideabi-4.8/prebuilt/%s/arm-linux-androideabi/bin/%s"
                % (sys_folder_name, strip_execute_name))
            if not os.path.exists(strip_cmd_path):
                strip_cmd_path = os.path.join(
                    ndk_root,
                    "toolchains/arm-linux-androideabi-4.8/prebuilt/%s/arm-linux-androideabi/bin/%s"
                    %
                    (sys_folder_name.replace(bit_str, ""), strip_execute_name))
            if os.path.exists(strip_cmd_path):
                armlibs = ["armeabi", "armeabi-v7a"]
                for fold in armlibs:
                    self.trip_libs(strip_cmd_path,
                                   os.path.join(android_out_dir, fold))

            # strip x86 libs
            strip_cmd_path = os.path.join(
                ndk_root,
                "toolchains/x86-4.8/prebuilt/%s/i686-linux-android/bin/%s" %
                (sys_folder_name, strip_execute_name))
            if os.path.exists(strip_cmd_path) and os.path.exists(
                    os.path.join(android_out_dir, "x86")):
                self.trip_libs(strip_cmd_path,
                               os.path.join(android_out_dir, 'x86'))
 def copy_template(self):
     for item in self.config_json[CocosBinTemplateGenerator.KEY_COPY_CONFIG]:
         excopy.copy_files_with_config(item, self.repo_x, self.engine_template_dir)
Example #39
0
    def do_build(self):
        print("Source Path : %s" % self.src_path)
        print("Output Path : %s" % self.dst_path)
        print("Start building")

        if os.path.exists(self.dst_path):
            shutil.rmtree(self.dst_path)

        # copy files
        copy_config = self.cfg_info[Builder.KEY_COPY_CONFIG]
        copy_cfgs = copy_config["common"]
        if sys.platform in copy_config:
            copy_cfgs += copy_config[sys.platform]
        elif os_is_linux():
            copy_cfgs += copy_config["linux"]

        for element in copy_cfgs:
            excopy.copy_files_with_config(element, self.src_path,
                                          self.dst_path)

        # modify files
        modify_config = self.cfg_info[Builder.KEY_MODIFY_CONFIG]
        for element in modify_config:
            self.modify_files(element)

        # get the path parameter
        plugins_path = os.path.join(self.src_path, "plugins")
        bin_path = os.path.join(self.src_path, "bin")
        dir_list = self._get_dirs(plugins_path)
        dir_list.append(plugins_path)
        dir_list.append(bin_path)
        dir_list.append(self.src_path)

        if os_is_win32():
            sep = ";"
        else:
            sep = ":"
        path_param = "-p %s" % sep.join(dir_list)

        # get the runtime-hook parameter
        _cp = ConfigParser.ConfigParser(allow_no_value=True)
        _cp.optionxform = str
        _cp.read(os.path.join(self.src_path, "bin/cocos2d.ini"))

        runtime_hook_param = ""
        hidden_import_param = ""

        # add hidden import params for config.json
        hidden_import_cfg = self.cfg_info[Builder.KEY_HIDDEN_IMPORT]
        if len(hidden_import_cfg) > 0:
            for key in hidden_import_cfg:
                hidden_import_param += "--hidden-import %s " % key
                runtime_hook_param += '--runtime-hook "%s" ' % os.path.join(
                    self.src_path, hidden_import_cfg[key])

        for s in _cp.sections():
            if s == 'plugins':
                for classname in _cp.options(s):
                    parts = classname.split(".")
                    module_name = parts[0]
                    hidden_import_param += "--hidden-import %s " % module_name

                    module_path = os.path.join(plugins_path, module_name)
                    if os.path.isdir(module_path):
                        runtime_hook_param += '--runtime-hook "%s" ' % (
                            "%s/__init__.py" % module_path)
                    else:
                        module_file = "%s.py" % module_path
                        if os.path.isfile(module_file):
                            runtime_hook_param += '--runtime-hook "%s" ' % module_file

        # additional hooks path
        add_hook_dir_param = '--additional-hooks-dir "%s" ' % plugins_path
        add_hook_dir_param += '--additional-hooks-dir "%s" ' % bin_path
        add_hook_dir_param += '--additional-hooks-dir "%s"' % self.src_path

        # build *.py
        if os_is_linux():
            spec_path = os.path.join(self.my_path, "build", "linux")
        else:
            spec_path = os.path.join(self.my_path, "build", sys.platform)
        work_path = spec_path
        if os.path.exists(spec_path):
            shutil.rmtree(spec_path)
        build_cmd = Builder.CMD_FORMAT % (
            path_param, '%s %s %s' %
            (hidden_import_param, add_hook_dir_param, runtime_hook_param),
            self.dst_path, spec_path, work_path, self.entrance_file)
        run_shell(build_cmd)

        print("Building succeed.")
Example #40
0
    def handle_for_android(self, module_info):
        # copy libs file
        android_lib_file_name = module_info[
            ModuleOrganizer.KEY_MODULE_ANDROID_LIB_FILE_NAME]
        copy_android_lib_cfg = {}
        copy_android_lib_cfg["from"] = "android"
        copy_android_lib_cfg["to"] = "%s/prebuilt/android" % module_info[
            ModuleOrganizer.KEY_MODULE_TARGET_DIR]
        copy_android_lib_cfg["include"] = ["*/%s.a" % android_lib_file_name]
        excopy.copy_files_with_config(copy_android_lib_cfg, self.prebuilt_dir,
                                      self.dst_root)

        # generate the prebuilt Android.mk for the module
        android_lib_name = module_info[
            ModuleOrganizer.KEY_MODULE_ANDROID_LIB_NAME]
        local_src_file = "./$(TARGET_ARCH_ABI)/%s.a" % android_lib_file_name
        export_include_paths = []
        for include_path in module_info[
                ModuleOrganizer.KEY_MODULE_EXPORT_INCLUDE]:
            temp_path = "${LOCAL_PATH}/%s" % include_path
            export_include_paths.append(temp_path)
        export_include_str = " \\\n".join(export_include_paths)

        export_ldlibs_str = ""
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_EXPORT_LDLIBS):
            export_ldlibs_str = "LOCAL_EXPORT_LDLIBS := "
            for ldlib in module_info[ModuleOrganizer.KEY_MODULE_EXPORT_LDLIBS]:
                export_ldlibs_str += ("-l%s " % ldlib)
            export_ldlibs_str += "\n\n"

        export_cflags_str = ""
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_EXPORT_CFLAGS):
            export_cflags_str = "LOCAL_EXPORT_CFLAGS := "
            export_cflags_str += " ".join(
                module_info[ModuleOrganizer.KEY_MODULE_EXPORT_CFLAGS])
            export_cflags_str += "\n\n"

        export_cppflags_str = ""
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_EXPORT_CPPFLAGS):
            export_cppflags_str = "LOCAL_EXPORT_CPPFLAGS := "
            export_cppflags_str += " ".join(
                module_info[ModuleOrganizer.KEY_MODULE_EXPORT_CPPFLAGS])
            export_cppflags_str += "\n\n"

        whole_libs = ""
        call_libs = ""
        if module_info.has_key(ModuleOrganizer.KEY_MODULE_DEPEND_MODULES):
            whole_libs, call_libs = self.gen_android_depend_str(
                module_info[ModuleOrganizer.KEY_MODULE_DEPEND_MODULES])

        mk_content = ModuleOrganizer.MK_FORMAT % \
                     (android_lib_name,
                      android_lib_file_name,
                      local_src_file,
                      export_include_str,
                      export_ldlibs_str,
                      export_cflags_str,
                      export_cppflags_str,
                      whole_libs,
                      call_libs
                     )

        mk_file_path = os.path.join(
            self.dst_root, module_info[ModuleOrganizer.KEY_MODULE_TARGET_DIR],
            "prebuilt/android/Android.mk")
        mk_dir = os.path.dirname(mk_file_path)
        if not os.path.exists(mk_dir):
            os.makedirs(mk_dir)
        mk_obj = open(mk_file_path, "w")
        mk_obj.write(mk_content)
        mk_obj.close()