Esempio n. 1
0
    def _gather_sign_info(self):
        user_cfg = {}
        # get the path of keystore file
        while True:
            inputed = self._get_user_input(MultiLanguage.get_string('COMPILE_TIP_INPUT_KEYSTORE'))
            inputed = inputed.strip()
            if not os.path.isabs(inputed):
                if self.use_studio:
                    start_path = os.path.join(self.app_android_root, 'app')
                else:
                    start_path = self.app_android_root
                abs_path = os.path.join(start_path, inputed)
            else:
                abs_path = inputed

            if os.path.isfile(abs_path):
                user_cfg[self.key_store_str] = inputed
                break
            else:
                cocos.Logging.warning(MultiLanguage.get_string('COMPILE_INFO_NOT_A_FILE'))

        # get the alias of keystore file
        user_cfg[self.key_alias_str] = self._get_user_input(MultiLanguage.get_string('COMPILE_TIP_INPUT_ALIAS'))

        # get the keystore password
        user_cfg[self.key_store_pass_str] = self._get_user_input(MultiLanguage.get_string('COMPILE_TIP_INPUT_KEY_PASS'))

        # get the alias password
        user_cfg[self.key_alias_pass_str] = self._get_user_input(MultiLanguage.get_string('COMPILE_TIP_INPUT_ALIAS_PASS'))

        # write the config into ant.properties
        self._write_sign_properties(user_cfg)
Esempio n. 2
0
    def parse_args(self, argv):
        """Custom and check param list.
        """
        parser = ArgumentParser(prog="cocos %s" % self.__class__.plugin_name(),
                                description=self.__class__.brief_description())
        parser.add_argument('-c', dest='clean', action="store_true",
                            help=MultiLanguage.get_string('GEN_LIBS_ARG_CLEAN'))
        parser.add_argument('-e', dest='engine_path', help=MultiLanguage.get_string('GEN_LIBS_ARG_ENGINE'))
        parser.add_argument('-p', dest='platform', action="append", choices=['ios', 'mac', 'android', 'win32'],
                            help=MultiLanguage.get_string('GEN_LIBS_ARG_PLATFORM'))
        parser.add_argument('-m', "--mode", dest='compile_mode', default='release', choices=['debug', 'release'],
                            help=MultiLanguage.get_string('GEN_LIBS_ARG_MODE'))
        parser.add_argument('--dis-strip', dest='disable_strip', action="store_true",
                            help=MultiLanguage.get_string('GEN_LIBS_ARG_DISABLE_STRIP'))
        group = parser.add_argument_group(MultiLanguage.get_string('GEN_LIBS_GROUP_WIN'))
        group.add_argument('--vs', dest='vs_version', type=int, default=None,
                           help=MultiLanguage.get_string('GEN_LIBS_ARG_VS'))
        group = parser.add_argument_group(MultiLanguage.get_string('GEN_LIBS_GROUP_ANDROID'))
        group.add_argument("--app-abi", dest="app_abi",
                            help=MultiLanguage.get_string('GEN_LIBS_ARG_ABI'))
        group.add_argument("--ap", dest="android_platform",
                            help=MultiLanguage.get_string('COMPILE_ARG_AP'))

        (args, unknown) = parser.parse_known_args(argv)
        self.init(args)

        return args
Esempio n. 3
0
    def _scan(self):
        template_pattern = {
            "cpp": 'cpp-template-(.+)',
            "lua": 'lua-template-(.+)',
            "js": 'js-template-(.+)',
        }

        self._template_folders = {}

        for templates_dir in self._templates_paths:
            try:
                dirs = [name for name in os.listdir(templates_dir) if os.path.isdir(
                    os.path.join(templates_dir, name))]
            except Exception:
                continue

            pattern = template_pattern[self._lang]
            for name in dirs:
                match = re.search(pattern, name)
                if match is None:
                    continue

                template_name = match.group(1)
                if template_name in self._template_folders.keys():
                    continue

                self._template_folders[template_name] = os.path.join(templates_dir, name)

        if len(self._template_folders) == 0:
            cur_engine = "cocos2d-x" if self._lang == "js" else "cocos2d-js"
            need_engine = "cocos2d-js" if self._lang == "js" else "cocos2d-x"
            engine_tip = MultiLanguage.get_string('NEW_ERROR_ENGINE_TIP_FMT', need_engine)
            message = MultiLanguage.get_string('NEW_ERROR_TEMPLATE_NOT_FOUND_FMT', (self._lang, engine_tip))
            raise cocos.CCPluginError(message, cocos.CCPluginError.ERROR_PATH_NOT_FOUND)
Esempio n. 4
0
    def __init__(self, lang, cocos_root, project_name, project_dir, tp_name, tp_dir, project_package, mac_id, ios_id):
        self.lang = lang
        self.cocos_root = cocos_root
        self.project_dir = project_dir
        self.project_name = project_name
        self.package_name = project_package
        self.mac_bundleid = mac_id
        self.ios_bundleid = ios_id

        self.tp_name = tp_name
        self.tp_dir = tp_dir
        self.tp_json = 'cocos-project-template.json'

        tp_json_path = os.path.join(tp_dir, self.tp_json)
        if not os.path.exists(tp_json_path):
            message = MultiLanguage.get_string('NEW_WARNING_FILE_NOT_FOUND_FMT', tp_json_path)
            raise cocos.CCPluginError(message, cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        f = open(tp_json_path)
        # keep the key order
        tpinfo = json.load(f, encoding='utf8', object_pairs_hook=OrderedDict)

        # read the default creating step
        if 'do_default' not in tpinfo:
            message = (MultiLanguage.get_string('NEW_ERROR_DEFAILT_CFG_NOT_FOUND_FMT', tp_json_path))
            raise cocos.CCPluginError(message, cocos.CCPluginError.ERROR_WRONG_CONFIG)
        self.tp_default_step = tpinfo.pop('do_default')
        # keep the other steps
        self.tp_other_step = tpinfo
Esempio n. 5
0
    def project_rename(self, v):
        """ will modify the file name of the file
        """
        dst_project_dir = self.project_dir
        dst_project_name = self.project_name
        src_project_name = v['src_project_name']
        if dst_project_name == src_project_name:
            return

        cocos.Logging.info(MultiLanguage.get_string('NEW_INFO_STEP_RENAME_PROJ_FMT',
                                                    (src_project_name, dst_project_name)))
        files = v['files']
        for f in files:
            src = f.replace("PROJECT_NAME", src_project_name)
            dst = f.replace("PROJECT_NAME", dst_project_name)
            src_file_path = os.path.join(dst_project_dir, src)
            dst_file_path = os.path.join(dst_project_dir, dst)
            if os.path.exists(src_file_path):
                if dst_project_name.lower() == src_project_name.lower():
                    temp_file_path = "%s-temp" % src_file_path
                    os.rename(src_file_path, temp_file_path)
                    os.rename(temp_file_path, dst_file_path)
                else:
                    if os.path.exists(dst_file_path):
                        os.remove(dst_file_path)
                    os.rename(src_file_path, dst_file_path)
            else:
                cocos.Logging.warning(MultiLanguage.get_string('NEW_WARNING_FILE_NOT_FOUND_FMT',
                                                               os.path.join(dst_project_dir, src)))
    def set_win32(self, proj_id, build_id):
        text = self.load_install_json()
        if text is None:
            print MultiLanguage.get_string("PACKAGE_ERROR_JSON_READ_FAILED")
            return

        find_tag = '(\{\s*"command":\s*"add_project",\s*"name":\s*"\S*",\s*"project_id":\s*")(\S*)(",\s*"build_id":\s*")(\S*)(",\s*"platform":\s*"win"\s*\})'
        match = re.search(find_tag, text, re.DOTALL)
        if not match is None:
            old_id = match.group(2)
            text = text.replace(old_id, proj_id)
            old_id = match.group(4)
            text = text.replace(old_id, build_id)
            self.save_install_json(text)
            return

        index = text.find("[")
        if index < 0:
            print MultiLanguage.get_string("PACKAGE_ERROR_JSON_ERROR")
            return

        headers = text[0 : index + 1]
        tails = text[index + 1 :]
        skip_str = "\n\t\t"
        str_to_add = "\n\t{"
        str_to_add += skip_str + '"command": "add_project",'
        str_to_add += skip_str + '"name": "' + self._package_name + '",'
        str_to_add += skip_str + '"project_id": "' + proj_id + '",'
        str_to_add += skip_str + '"build_id": "' + build_id + '",'
        str_to_add += skip_str + '"platform": "win"'
        str_to_add += "\n\t},"
        text = headers + str_to_add + tails
        self.save_install_json(text)
Esempio n. 7
0
    def run(self, argv, dependencies):
        """
        """
        self.parse_args(argv)

        # create output directory
        try:
            os.makedirs(self._dst_dir)
        except OSError:
            if os.path.exists(self._dst_dir) == False:
                raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_MKDIR_FAILED_FMT', self._dst_dir),
                                          cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        # download the bin folder
        jsbcc_exe_path = os.path.join(self._workingdir, "bin", "jsbcc")
        if not os.path.exists(jsbcc_exe_path):
            download_cmd_path = os.path.join(self._workingdir, os.pardir, os.pardir)
            subprocess.call("python %s -f -r no" % (os.path.join(download_cmd_path, "download-bin.py")), shell=True, cwd=download_cmd_path)

        # deep iterate the src directory
        for src_dir in self._src_dir_arr:
            self._current_src_dir = src_dir
            self._js_files[self._current_src_dir] = []
            self.deep_iterate_dir(src_dir)

        self.reorder_js_files()
        self.handle_all_js_files()
        cocos.Logging.info(MultiLanguage.get_string('LUACOMPILE_INFO_FINISHED'))
Esempio n. 8
0
    def load_proj_ios_mac(self, notSplitLines = False):
        if not "proj.ios_mac" in self._project:
            print MultiLanguage.get_string('PACKAGE_MAC_NOT_FOUND')
            return

        workdir = self._project["proj.ios_mac"]
        files = os.listdir(workdir)
        for filename in files:
            if filename[-10:] == ".xcodeproj":
                proj_dir = filename
                break

        if proj_dir is None:
            print MultiLanguage.get_string('PACKAGE_XCODE_PROJ_NOT_FOUND')
            return

        if not os.path.isdir(workdir + os.sep + proj_dir):
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_NOT_XCODE_PROJ_FMT', proj_dir),
                                      cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        proj_file_path = workdir + os.sep + proj_dir + os.sep + "project.pbxproj"
        f = open(proj_file_path, "rb")
        if notSplitLines == True:
            lines = f.read()
        else:
            lines = f.readlines()
        f.close()

        return workdir, proj_file_path, lines
Esempio n. 9
0
    def add_files_and_dir(self, command):
        backup_flag = command["backup_if_override"]
        package_name = self._package_name
        file_list = command["source"]
        src_dir = self._package_path + os.sep + command["src_dir"]
        dst_dir = self._project["path"] + os.sep + command["dst_dir"]

        for filename in file_list:
            src = src_dir + os.sep + filename
            dst = dst_dir + os.sep + filename

            if os.path.exists(dst):
                if backup_flag:
                    bak = dst + "_bak_by_" + package_name
                    if not os.path.exists(bak):
                        os.rename(dst, bak)
                        self.append_uninstall_info({'bak_file':bak, 'ori_file':dst})
                        self.save_uninstall_info()
                    else:
                        print MultiLanguage.get_string('PACKAGE_UNABLE_COPY_FMT', dst)
                        continue
                else:
                    if os.path.isdir(dst):
                        shutil.rmtree(dst)
                    else:
                        os.remove(dst)
            else:
                ensure_directory(os.path.dirname(dst))

            if os.path.isdir(src):
                shutil.copytree(src, dst)
            else:
                shutil.copy(src, dst)
Esempio n. 10
0
    def get_build_cfg_json_path(self):
        file_path = self._project["proj.android"] + os.sep + "build-cfg.json"
        if not os.path.isfile(file_path):
            print MultiLanguage.get_string('PACKAGE_BUILD_CFG_NOT_FOUND')
            return

        return file_path
Esempio n. 11
0
    def add_entry_function(self, command):
        declare_str = command["declare"]
        find_tag = '(\S*\s*)(\S*)(\(.*\);)'
        match = re.search(find_tag, declare_str)
        if match is None:
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_ENTRY_DECLARE_FAILED'),
                                      cocos.CCPluginError.ERROR_PARSE_FILE)
        else:
            str_to_add = 'extern ' + declare_str + '\n\t' + match.group(2) + '();' + '\n\t'

        file_path, all_text = self.load_appdelegate_file()
        find_tag = '(static int register_all_packages\(\)\s*\{.*)(return 0; //flag for packages manager\s*\})'
        match = re.search(find_tag, all_text, re.DOTALL)
        if match is None:
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_ERROR_IN_FILE_FMT', file_path),
                                      cocos.CCPluginError.ERROR_PARSE_FILE)
        else:
            # add entry funtion
            split_index = match.end(1)
            headers = all_text[0:split_index]
            tails = all_text[split_index:]
            all_text = headers + str_to_add + tails
            self.append_uninstall_info({'file':file_path, 'string':str_to_add})

        self.update_file_content(file_path, all_text)
Esempio n. 12
0
    def update_framework(cls, project, package_name):
        cls.show_project_info(project)

        package = cls.check_added_package(project, package_name)
        if package is None:
            print MultiLanguage.get_string('PACKAGE_PKG_NOT_FOUND_FMT', package_name)
            return

        engine = get_engine_of_project(project)
        if engine is None:
            print MultiLanguage.get_string('PACKAGE_PROJ_UNKOWN_ENGINE')
            return

        package_data = PackageHelper.get_installed_package_newest_version(package_name, engine)
        if package_data is None:
            print MultiLanguage.get_string('PACKAGE_NOT_FOUND_PKG_FMT', (package_name, engine, package_name))
            return
        newest_version = package_data["version"]

        dir = package["dir_path"]
        if compare_version(newest_version, package["version"]) < 1:
            print MultiLanguage.get_string('PACKAGE_PKG_IS_NEWEST_FMT', (package_name, package_name))
            return
        cls.remove_framework(project, package_name)
        cls.add_framework(project, package_name)
        print MultiLanguage.get_string('PACKAGE_PROJ_PKG_UPDATE_OK')
Esempio n. 13
0
    def parse_args(self, argv):
        if len(argv) < 1:
            print "usage: cocos framework [-h] COMMAND arg [arg ...]"
            print MultiLanguage.get_string('FRAMEWORK_ERROR_TOO_FEW_ARGS')
            return None

        return {"command": argv[0]}
Esempio n. 14
0
    def run(self, argv, dependencies):
        """
        """
        self.parse_args(argv)

        # tips
        cocos.Logging.warning(MultiLanguage.get_string("LUACOMPILE_WARNING_TIP_MSG"))
        # create output directory
        try:
            os.makedirs(self._dst_dir)
        except OSError:
            if os.path.exists(self._dst_dir) == False:
                raise cocos.CCPluginError(
                    MultiLanguage.get_string("LUACOMPILE_ERROR_MKDIR_FAILED_FMT", self._dst_dir),
                    cocos.CCPluginError.ERROR_PATH_NOT_FOUND,
                )

        # deep iterate the src directory
        for src_dir in self._src_dir_arr:
            self._current_src_dir = src_dir
            self._lua_files[self._current_src_dir] = []
            self.deep_iterate_dir(src_dir)

        self.handle_all_lua_files()

        cocos.Logging.info(MultiLanguage.get_string("LUACOMPILE_INFO_FINISHED"))
Esempio n. 15
0
    def parse_args(self, argv):
        from argparse import ArgumentParser

        parser = ArgumentParser(prog="cocos package %s" % self.__class__.plugin_name(),
                                description=self.__class__.brief_description())
        parser.add_argument("name", metavar="NAME", help=MultiLanguage.get_string('PACKAGE_INFO_ARG_NAME'))
        parser.add_argument('-v', '--version', default='all', help=MultiLanguage.get_string('PACKAGE_INFO_ARG_VERSION'))
        return parser.parse_args(argv)
Esempio n. 16
0
    def set_framework(cls, project, package_name, version):
        cls.show_project_info(project)
        packages_dir = project["packages_dir"]
        if not os.path.isdir(packages_dir):
            print MultiLanguage.get_string('PACKAGE_NO_PKG_FOUND')
            return

        set_helper = SetFrameworkHelper(project, package_name, version)
        set_helper.run()
Esempio n. 17
0
 def remove_package(self, package_data):
     key = package_data["name"] + "-" + package_data["version"]
     if key in self._data:
         del self._data[key]
         self.update_database()
         print MultiLanguage.get_string('PACKAGE_PKG_REMOVE_OK_FMT', key)
     else:
         message = MultiLanguage.get_string('PACKAGE_PKG_NOT_FOUND_PKG_FMT', key)
         raise cocos.CCPluginError(message, cocos.CCPluginError.ERROR_WRONG_CONFIG)
Esempio n. 18
0
    def parse_args(self, argv):
        """
        """
        from argparse import ArgumentParser

        parser = ArgumentParser(prog="cocos %s" % self.__class__.plugin_name(),
                                description=self.__class__.brief_description())
        parser.add_argument("-v", "--verbose",
                          action="store_true",
                          dest="verbose",
                          help=MultiLanguage.get_string('LUACOMPILE_ARG_VERBOSE'))
        parser.add_argument("-s", "--src",
                          action="append", dest="src_dir_arr",
                          help=MultiLanguage.get_string('JSCOMPILE_ARG_SRC'))

        parser.add_argument("-d", "--dst",
                          action="store", dest="dst_dir",
                          help=MultiLanguage.get_string('JSCOMPILE_ARG_DST'))

        parser.add_argument("-c", "--use_closure_compiler",
                          action="store_true", dest="use_closure_compiler", default=False,
                          help=MultiLanguage.get_string('JSCOMPILE_ARG_CLOSURE'))

        parser.add_argument("-o", "--output_compressed_filename",
                          action="store", dest="compressed_filename", default="game.min.js",
                          help=MultiLanguage.get_string('JSCOMPILE_ARG_OUT_FILE_NAME'))

        parser.add_argument("-j", "--compiler_config",
                          action="store", dest="compiler_config",
                          help=MultiLanguage.get_string('JSCOMPILE_ARG_JSON_FILE'))
        parser.add_argument("-m", "--closure_params",
                          action="store", dest="closure_params",
                          help=MultiLanguage.get_string('JSCOMPILE_ARG_EXTRA_PARAM'))

        options = parser.parse_args(argv)

        if options.src_dir_arr == None:
            raise cocos.CCPluginError(MultiLanguage.get_string('JSCOMPILE_ERROR_SRC_NOT_SPECIFIED'),
                                      cocos.CCPluginError.ERROR_WRONG_ARGS)
        elif options.dst_dir == None:
            raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_DST_NOT_SPECIFIED'),
                                      cocos.CCPluginError.ERROR_WRONG_ARGS)
        else:
            for src_dir in options.src_dir_arr:
                if os.path.exists(src_dir) == False:
                    raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_DIR_NOT_EXISTED_FMT',
                                                                       (src_dir)),
                                              cocos.CCPluginError.ERROR_PATH_NOT_FOUND)


        # script directory
        if getattr(sys, 'frozen', None):
            workingdir = os.path.realpath(os.path.dirname(sys.executable))
        else:
            workingdir = os.path.realpath(os.path.dirname(__file__))

        self.init(options, workingdir)
Esempio n. 19
0
    def add_header_path_on_ios_mac(self, source, platform):
        if platform == "ios":
            tag = self.__class__.IOS_HEADER_MATCH_TAG
        elif platform == "mac":
            tag = self.__class__.MAC_HEADER_MATCH_TAG
        else:
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_ERROR_INVALID_PLATFORM_FMT', platform),
                                      cocos.CCPluginError.ERROR_WRONG_ARGS)

        workdir, proj_file_path, lines = self.load_proj_ios_mac()
        contents = []
        tag_found = False
        for line in lines:
            match = re.search(tag, line)
            if match is None:
                contents.append(line)
            else:
                includes = shlex.split(match.group(2))
                headers = []
                for include in includes:
                    include = self.get_ios_mac_path(workdir, include)
                    headers.append(include)

                str_to_add = self.get_ios_mac_path(workdir, source)
                headers.append(str_to_add)
                headers = list(set(headers))
                start, end = match.span(0)
                parts = []
                parts.append(line[:start])
                parts.append(match.group(1))
                parts.append(' ')
                for header in headers:
                    if header.find(' ') != -1:
                        header = '"' + header + '"'
                    parts.append(header)
                    parts.append(' ')
                parts.append(match.group(3))
                parts.append(line[end:])
                contents.append(''.join(parts))
                tag_found = True

        if tag_found == False:
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_TAG_NOT_FOUND_FMT',
                                      ("header", platform)),
                                      cocos.CCPluginError.ERROR_PARSE_FILE)
        else:
            uninst_info = {
                'file': proj_file_path,
                'tags': [tag],
                'type': "header",
                'platform': "ios_mac",
                'workdir': workdir,
                'string':str_to_add
            }
            self.append_uninstall_info(uninst_info)
            self.update_file_content(proj_file_path, contents, True)
    def copy_file_from_template(self, src, dst):
        f = open(src, "rb")
        text = f.read()
        f.close()
        text = self.get_format_string(text)

        f = open(dst, "wb")
        f.write(text)
        f.close()
        print MultiLanguage.get_string("PACKAGE_CREATE_OK_FMT", dst)
Esempio n. 21
0
    def get_relative_path(self, luafile):
        try:
            pos = luafile.index(self._current_src_dir)
            if pos != 0:
                raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_SRCDIR_NAME_NOT_FOUND'),
                                          cocos.CCPluginError.ERROR_WRONG_ARGS)

            return luafile[len(self._current_src_dir)+1:]
        except ValueError:
            raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_SRCDIR_NAME_NOT_FOUND'),
                                      cocos.CCPluginError.ERROR_WRONG_ARGS)
    def load_install_json(self):
        install_json_file = self._package_path + os.sep + "install.json"
        if not os.path.isfile(install_json_file):
            print MultiLanguage.get_string("PACKAGE_ERROR_NOT_FOUND_JSON")
            return

        f = open(install_json_file, "rb")
        text = f.read()
        f.close()

        return text
Esempio n. 23
0
    def load_appdelegate_file(self):
        file_path = self._project["classes_dir"] + os.sep + "AppDelegate.cpp"
        if not os.path.isfile(file_path):
            print MultiLanguage.get_string('PACKAGE_APPDELEGATE_NOT_FOUND')
            return

        f = open(file_path, "rb")
        all_text = f.read()
        f.close()

        return file_path, all_text
Esempio n. 24
0
    def do_add_project_on_android(self, command):
        proj_name = command["name"].encode('UTF-8')

        build_cfg_file = self.get_build_cfg_json_path()
        if build_cfg_file is None:
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_BUILD_CFG_NOT_FOUND'),
                                      cocos.CCPluginError.ERROR_PATH_NOT_FOUND)
        f = open(build_cfg_file, "rb")
        configs = json.load(f)
        f.close()
        if not isinstance(configs["ndk_module_path"], list):
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_NDK_MODULE_NOT_FOUND'),
                                      cocos.CCPluginError.ERROR_WRONG_CONFIG)
        moudle_path = '../../../packages/' + self._package_name + '-' + self._package_version
        configs["ndk_module_path"].append(moudle_path)
        self.append_uninstall_info({'json_file':build_cfg_file, 'items':[{'key':'ndk_module_path','items':[moudle_path]}]})
        self.save_uninstall_info()
        f = open(build_cfg_file, "w+b")
        str = json.dump(configs, f)
        f.close()

        workdir, proj_pbx_path, all_text = self.load_proj_android(True)

        find_tag = '(' + self.__class__.ANDROID_LIB_BEGIN_TAG+ ')(.*)(' + self.__class__.ANDROID_LIB_END_TAG + ')'
        match = re.search(find_tag, all_text, re.DOTALL)
        if match is None:
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_TAG_NOT_FOUND_FMT',
                                      ("lib", "android")),
                                      cocos.CCPluginError.ERROR_PARSE_FILE)
        else:
            # add project
            split_index = match.end(2)
            headers = all_text[0:split_index]
            tails = all_text[split_index:]
            str_to_add = 'LOCAL_STATIC_LIBRARIES += ' + proj_name + '_static\n'
            all_text = headers + str_to_add + tails
            self.append_uninstall_info({'file':proj_pbx_path, 'string':str_to_add})

        find_tag = '(' + self.__class__.ANDROID_LIB_IMPORT_BEGIN_TAG+ ')(.*)(' + self.__class__.ANDROID_LIB_IMPORT_END_TAG + ')'
        match = re.search(find_tag, all_text, re.DOTALL)
        if match is None:
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_TAG_NOT_FOUND_FMT',
                                      ("lib", "android")),
                                      cocos.CCPluginError.ERROR_PARSE_FILE)
        else:
            # add import moudle
            split_index = match.end(2)
            headers = all_text[0:split_index]
            tails = all_text[split_index:]
            str_to_add = '$(call import-module,proj.android)\n'
            all_text = headers + str_to_add + tails
            self.append_uninstall_info({'file':proj_pbx_path, 'string':str_to_add})

        self.update_file_content(proj_pbx_path, all_text)
Esempio n. 25
0
    def add_lib_on_ios_mac(self, source, platform):
        if platform == "ios":
            begin_tag = self.__class__.IOS_LIB_BEGIN_TAG
            end_tag = self.__class__.IOS_LIB_END_TAG
        elif platform == "mac":
            begin_tag = self.__class__.MAC_LIB_BEGIN_TAG
            end_tag = self.__class__.MAC_LIB_END_TAG
        else:
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_ERROR_INVALID_PLATFORM_FMT', platform),
                                      cocos.CCPluginError.ERROR_WRONG_ARGS)

        workdir, proj_pbx_path, lines = self.load_proj_ios_mac()
        contents = []
        lib_begin = False
        tag_found = False
        libs = []
        for line in lines:
            if lib_begin == False:
                contents.append(line)
                match = re.search(begin_tag, line)
                if not match is None:
                    lib_begin = True
                    tag_found = True
            else:
                match = re.search(end_tag, line)
                if match is None:
                    libs.append(self.get_ios_mac_path(workdir, line))
                else:
                    # add new lib to libs
                    str_to_add = self.get_ios_mac_path(workdir, source)
                    libs.append(str_to_add)
                    libs = list(set(libs))
                    for lib in libs:
                        contents.append('\t\t\t\t\t"' + lib + '",\n')

                    libs = []
                    lib_begin = False
                    contents.append(line)

        if tag_found == False:
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_TAG_NOT_FOUND_FMT',
                                      ("lib",  platform)),
                                      cocos.CCPluginError.ERROR_PARSE_FILE)
        else:
            uninst_info = {
                'file': proj_pbx_path,
                'tags': [begin_tag, end_tag],
                'type': "lib",
                'platform': "ios_mac",
                'workdir': workdir,
                'string':str_to_add
            }
            self.append_uninstall_info(uninst_info)
            self.update_file_content(proj_pbx_path, contents, True)
Esempio n. 26
0
 def run_cmd(command, verbose, cwd=None):
     if verbose:
         Logging.debug(MultiLanguage.get_string('COCOS_DEBUG_RUNNING_CMD_FMT', ''.join(command)))
     else:
         log_path = CCPlugin._log_path()
         command += ' >"%s" 2>&1' % log_path
     ret = subprocess.call(command, shell=True, cwd=cwd)
     if ret != 0:
         message = MultiLanguage.get_string('COCOS_ERROR_RUNNING_CMD_RET_FMT', str(ret))
         if not verbose:
             message += (MultiLanguage.get_string('COCOS_ERROR_CHECK_LOG_FMT', log_path))
         raise CCPluginError(message, CCPluginError.ERROR_RUNNING_CMD)
Esempio n. 27
0
    def append_x_engine(self, v):
        # FIXME this is a hack, but in order to fix it correctly the cocos-project-template.json
        # file probably will need to be re-designed.
        # As a quick (horrible) fix, we check if we are in distro mode.
        # If so, we don't do the "append_x_engine" step
        if cocos.CCPlugin.get_cocos2d_mode() == 'distro':
            return

        src = os.path.join(self.cocos_root, v['from'])
        dst = os.path.join(self.project_dir, v['to'])

        # check cocos engine exist
        cocosx_files_json = os.path.join(
            src, 'templates', 'cocos2dx_files.json')
        if not os.path.exists(cocosx_files_json):
            message = MultiLanguage.get_string('NEW_WARNING_FILE_NOT_FOUND_FMT', cocosx_files_json)
            raise cocos.CCPluginError(message, cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        f = open(cocosx_files_json)
        data = json.load(f)
        f.close()

        fileList = data['common']
        if self.lang == 'lua':
            fileList = fileList + data['lua']

        if self.lang == 'js' and 'js' in data.keys():
            fileList = fileList + data['js']

        # begin copy engine
        cocos.Logging.info(MultiLanguage.get_string('NEW_INFO_STEP_COPY_X'))

        for index in range(len(fileList)):
            srcfile = os.path.join(src, fileList[index])
            dstfile = os.path.join(dst, fileList[index])

            srcfile = cocos.add_path_prefix(srcfile)
            dstfile = cocos.add_path_prefix(dstfile)

            if not os.path.exists(os.path.dirname(dstfile)):
                os.makedirs(cocos.add_path_prefix(os.path.dirname(dstfile)))

            # copy file or folder
            if os.path.exists(srcfile):
                if os.path.isdir(srcfile):
                    if os.path.exists(dstfile):
                        shutil.rmtree(dstfile)
                    shutil.copytree(srcfile, dstfile)
                else:
                    if os.path.exists(dstfile):
                        os.remove(dstfile)
                    shutil.copy2(srcfile, dstfile)
Esempio n. 28
0
 def get_relative_path(self, jsfile):
     try:
         # print "current src dir: "+self._current_src_dir)
         pos = jsfile.index(self._current_src_dir)
         if pos != 0:
             raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_SRCDIR_NAME_NOT_FOUND'),
                                       cocos.CCPluginError.ERROR_WRONG_ARGS)
         # print "origin js path: "+ jsfile
         # print "relative path: "+jsfile[len(self._current_src_dir)+1:]
         return jsfile[len(self._current_src_dir)+1:]
     except ValueError:
         raise cocos.CCPluginError(MultiLanguage.get_string('LUACOMPILE_ERROR_SRCDIR_NAME_NOT_FOUND'),
                                   cocos.CCPluginError.ERROR_WRONG_ARGS)
Esempio n. 29
0
    def do_other_step(self, step, not_existed_error=True):
        if step not in self.tp_other_step:
            if not_existed_error:
                # handle as error
                message = MultiLanguage.get_string('NEW_ERROR_STEP_NOT_FOUND_FMT', step)
                raise cocos.CCPluginError(message, cocos.CCPluginError.ERROR_WRONG_CONFIG)
            else:
                # handle as warning
                cocos.Logging.warning(MultiLanguage.get_string('NEW_WARNING_STEP_NOT_FOUND_FMT', step))
                return

        cmds = self.tp_other_step[step]
        self.do_cmds(cmds)
Esempio n. 30
0
    def run_web(self, dependencies):
        if not self._platforms.is_web_active():
            return

        from SimpleHTTPServer import SimpleHTTPRequestHandler
        HandlerClass = SimpleHTTPRequestHandler
        ServerClass  = BaseHTTPServer.HTTPServer
        Protocol     = "HTTP/1.0"
        HandlerClass.protocol_version = Protocol

        host = self._host
        if self._port is None:
            port = 8000
            port_max_add = 2000
        else:
            port = int(self._port)
            port_max_add = 0

        deploy_dep = dependencies['deploy']
        run_root = deploy_dep.run_root

        i = 0
        httpd = None
        while (i <= port_max_add):
            port += i
            i += 1
            server_address = (host, port)
            try:
                cocos.Logging.info(MultiLanguage.get_string('RUN_INFO_HOST_PORT_FMT', (host, port)))
                httpd = ServerClass(server_address, HandlerClass)
            except Exception as e:
                httpd = None
                cocos.Logging.warning(MultiLanguage.get_string('RUN_WARNING_SERVER_FAILED_FMT', (host, port, e)))

            if httpd is not None:
                break

        if httpd is None:
            raise cocos.CCPluginError(MultiLanguage.get_string('RUN_ERROR_START_SERVER_FAILED'),
                                      cocos.CCPluginError.ERROR_OTHERS)

        from threading import Thread
        sub_url = deploy_dep.sub_url
        url = 'http://%s:%s%s' % (host, port, sub_url)
        thread = Thread(target = self.open_webbrowser, args = (url,))
        thread.start()

        sa = httpd.socket.getsockname()
        with cocos.pushd(run_root):
            cocos.Logging.info(MultiLanguage.get_string('RUN_INFO_SERVING_FMT', (sa[0], sa[1])))
            httpd.serve_forever()
Esempio n. 31
0
    def do_ndk_build(self, ndk_build_param, build_mode, compile_obj):
        cocos.Logging.info(MultiLanguage.get_string('COMPILE_INFO_NDK_MODE', build_mode))
        ndk_root = cocos.check_environment_variable('NDK_ROOT')

        toolchain_version = self.get_toolchain_version(ndk_root, compile_obj)

        if self.use_studio:
            ndk_work_dir = os.path.join(self.app_android_root, 'app')
        else:
            ndk_work_dir = self.app_android_root
        reload(sys)
        sys.setdefaultencoding('utf8')
        ndk_path = cocos.CMDRunner.convert_path_to_cmd(os.path.join(ndk_root, "ndk-build"))

        module_paths = []
        for cfg_path in self.ndk_module_paths:
            if cfg_path.find("${COCOS_X_ROOT}") >= 0:
                cocos_root = cocos.check_environment_variable("COCOS_X_ROOT")
                module_paths.append(cfg_path.replace("${COCOS_X_ROOT}", cocos_root))
            elif cfg_path.find("${COCOS_FRAMEWORKS}") >= 0:
                cocos_frameworks = cocos.check_environment_variable("COCOS_FRAMEWORKS")
                module_paths.append(cfg_path.replace("${COCOS_FRAMEWORKS}", cocos_frameworks))
            else:
                module_paths.append(os.path.join(self.app_android_root, cfg_path))

        # delete template static and dynamic files
        obj_local_dir = os.path.join(ndk_work_dir, "obj", "local")
        if os.path.isdir(obj_local_dir):
            for abi_dir in os.listdir(obj_local_dir):
                static_file_path = os.path.join(ndk_work_dir, "obj", "local", abi_dir)
                if os.path.isdir(static_file_path):
                    self.remove_c_libs(static_file_path)
           	    
        # windows should use ";" to seperate module paths
        if cocos.os_is_win32():
            ndk_module_path = ';'.join(module_paths)
        else:
            ndk_module_path = ':'.join(module_paths)
        
        ndk_module_path= 'NDK_MODULE_PATH=' + ndk_module_path

        if ndk_build_param is None:
            ndk_build_cmd = '%s -C %s %s' % (ndk_path, ndk_work_dir, ndk_module_path)
        else:
            ndk_build_cmd = '%s -C %s %s %s' % (ndk_path, ndk_work_dir, ' '.join(ndk_build_param), ndk_module_path)

        ndk_build_cmd = '%s NDK_TOOLCHAIN_VERSION=%s' % (ndk_build_cmd, toolchain_version)

        if build_mode == 'debug':
            ndk_build_cmd = '%s NDK_DEBUG=1' % ndk_build_cmd

        self._run_cmd(ndk_build_cmd)
Esempio n. 32
0
    def find_xap_deploy_tool(self):
        import _winreg
        import re
        if cocos.os_is_32bit_windows():
            reg_flag_list = [ _winreg.KEY_WOW64_32KEY ]
        else:
            reg_flag_list = [ _winreg.KEY_WOW64_64KEY, _winreg.KEY_WOW64_32KEY ]

        pattern = re.compile(r"v(\d+).(\d+)")
        find_ret = None
        find_major = -1
        find_minor = -1
        for reg_flag in reg_flag_list:
            cocos.Logging.info(MultiLanguage.get_string('DEPLOY_INFO_FIND_XAP_FMT',
                                                        ("32bit" if reg_flag == _winreg.KEY_WOW64_32KEY else "64bit")))
            try:
                wp = _winreg.OpenKey(
                    _winreg.HKEY_LOCAL_MACHINE,
                    r"SOFTWARE\Microsoft\Microsoft SDKs\WindowsPhone",
                    0,
                    _winreg.KEY_READ | reg_flag
                )
            except:
                # windows phone not found, continue
                continue

            i = 0
            while True:
                try:
                    version = _winreg.EnumKey(wp, i)
                except:
                    break

                i += 1
                match = re.match(pattern, version)
                if match:
                    major = int(match.group(1))
                    minor = int(match.group(2))
                    if major > 7:
                        try:
                            key = _winreg.OpenKey(wp, "%s\Install Path" % version)
                            value, type = _winreg.QueryValueEx(key, "Install Path")
                            tool_path = os.path.join(value, "Tools", "XAP Deployment", "XapDeployCmd.exe")
                            if os.path.isfile(tool_path):
                                if (find_ret is None) or (major > find_major) or (major == find_major and minor > find_minor):
                                    find_ret = tool_path
                                    find_major = major
                                    find_minor = minor
                        except:
                            pass

        return find_ret
    def check_android_platform(self, sdk_root, android_platform, proj_path):
        ret = android_platform
        if android_platform is None:
            min_platform = self.get_target_config(proj_path)
            # not specified platform, use the one in project.properties
            ret = 'android-%d' % min_platform

        ret_path = os.path.join(cocos.CMDRunner.convert_path_to_python(sdk_root), "platforms", ret)
        if not os.path.isdir(ret_path):
            raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_NO_AP_IN_SDK_FMT', ret),
                                      cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        return ret
Esempio n. 34
0
    def project_replace_so_name(self, v):
        """ will modify the content of the file
        """
        src_so_name = v['src_so_name']
        dst_so_name = self.project_name
        if src_so_name == dst_so_name:
            return

        cocos.Logging.info(MultiLanguage.get_string('NEW_INFO_STEP_REPLACE_SO_FMT',
                                                    (src_so_name, dst_so_name)))
        files = v['files']
        if not dst_so_name:
            raise cocos.CCPluginError(MultiLanguage.get_string('NEW_ERROR_PKG_NAME_NOT_SPECIFIED'),
                                      cocos.CCPluginError.ERROR_WRONG_ARGS)
        for f in files:
            dst = f.replace("PROJECT_NAME", self.project_name)
            dstpath = os.path.join(self.project_dir, dst)
            if os.path.exists(dstpath):
                replace_string(dstpath, src_so_name, dst_so_name)
            else:
                cocos.Logging.warning(MultiLanguage.get_string('NEW_WARNING_FILE_NOT_FOUND_FMT',
                                                               dstpath))
Esempio n. 35
0
    def download_zip_file(self):
        if os.path.isfile(self._filename):
            if self._force or not self.check_file_md5():
                os.remove(self._filename)
            else:
                print MultiLanguage.get_string('PACKAGE_EXISTS_FMT',
                                               self._filename)

        if not os.path.isfile(self._filename):
            self.download_file()

        try:
            if not zipfile.is_zipfile(self._filename):
                raise UnrecognizedFormat(
                    MultiLanguage.get_string('PACKAGE_ERROR_NOT_ZIP_FMT',
                                             (self._filename)))
        except UnrecognizedFormat as e:
            print(
                MultiLanguage.get_string('PACKAGE_ERROR_UNKNOWN_FORMAT_FMT',
                                         self._filename))
            if os.path.isfile(self._filename):
                os.remove(self._filename)
Esempio n. 36
0
    def run(self):
        package_name = self._package_name
        package_path = self._package_path
        if not os.path.isdir(package_path):
            raise cocos.CCPluginError(
                MultiLanguage.get_string('PACKAGE_ERROR_PATH_NOT_FOUND_FMT',
                                         package_path),
                cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        sln_txt = self.load_sln_win32()
        if sln_txt is None:
            print MultiLanguage.get_string('PACKAGE_ERROR_READ_SLN')
        else:
            find_tag = '(Project\(\"\{)(\S*)(\}\"\) = \"' + package_name + '\", \"\S*\", \"\{)(\S*)(\}\"\s*EndProject)'
            match = re.search(find_tag, sln_txt, re.DOTALL)
            if match is None:
                print MultiLanguage.get_string('PACKAGE_ERROR_NOT_FOUND_PROJ',
                                               package_name)
            else:
                proj_id_win = match.group(2)
                build_id_win = match.group(4)
                self.set_win32(proj_id_win, build_id_win)
Esempio n. 37
0
 def run(self, argv, dependencies):
     if '--anysdk' in argv:
         argv.remove('--anysdk')
         cmd = self._get_cocospackage_path() + ' --runincocos ' + ' '.join(argv)
         ret = self._run_cmd(cmd)
     else:
         if '--sdkbox' in argv:
             argv.remove('--sdkbox')
         cmd = self._get_sdkbox_path() + ' --runincocos ' + ' '.join(argv)
         ret = self._run_cmd(cmd)
     if 0 != ret:
         message = MultiLanguage.get_string('COCOS_ERROR_RUNNING_CMD_RET_FMT', str(ret))
         raise cocos.CCPluginError(message, cocos.CCPluginError.ERROR_RUNNING_CMD)
Esempio n. 38
0
    def __init__(self, lang, cocos_root, project_name, project_dir, tp_name,
                 tp_dir, project_package, mac_id, ios_id):
        self.lang = lang
        self.cocos_root = cocos_root
        self.project_dir = project_dir
        self.project_name = project_name
        self.package_name = project_package
        self.mac_bundleid = mac_id
        self.ios_bundleid = ios_id

        self.tp_name = tp_name
        self.tp_dir = tp_dir
        self.tp_json = 'cocos-project-template.json'

        # search in 'template_metadata' first
        tp_json_path = os.path.join(tp_dir, 'template_metadata', self.tp_json)
        if not os.path.exists(tp_json_path):
            # if not, search in the old place
            tp_json_path = os.path.join(tp_dir, self.tp_json)

        if not os.path.exists(tp_json_path):
            message = MultiLanguage.get_string(
                'NEW_WARNING_FILE_NOT_FOUND_FMT', tp_json_path)
            raise cocos.CCPluginError(message,
                                      cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        f = open(tp_json_path)
        # keep the key order
        tpinfo = json.load(f, encoding='utf8', object_pairs_hook=OrderedDict)

        # read the default creating step
        if 'do_default' not in tpinfo:
            message = (MultiLanguage.get_string(
                'NEW_ERROR_DEFAILT_CFG_NOT_FOUND_FMT', tp_json_path))
            raise cocos.CCPluginError(message,
                                      cocos.CCPluginError.ERROR_WRONG_CONFIG)
        self.tp_default_step = tpinfo.pop('do_default')
        # keep the other steps
        self.tp_other_step = tpinfo
Esempio n. 39
0
def check_environment_variable(var):
    ''' Checking the environment variable, if found then return it's value, else raise error
    '''
    try:
        value = ExtendEnv.get_extend_env_value(var)
        if value is None:
            value = os.environ[var]
    except Exception:
        raise CCPluginError(
            MultiLanguage.get_string('COCOS_ERROR_ENV_NOT_DEFINED_FMT', var),
            CCPluginError.ERROR_ENV_VAR_NOT_FOUND)

    return value
    def check_platform(self, platform):
        if platform == 'mac':
            if not self._platforms.is_mac_active() or not cocos.os_is_mac:
                raise cocos.CCPluginError(
                    MultiLanguage.get_string('COMPILE_ERROR_BUILD_ON_MAC'),
                    cocos.CCPluginError.ERROR_WRONG_ARGS)

        if platform == 'ios':
            if not self._platforms.is_ios_active() or not cocos.os_is_mac:
                raise cocos.CCPluginError(
                    MultiLanguage.get_string('COMPILE_ERROR_BUILD_ON_MAC'),
                    cocos.CCPluginError.ERROR_WRONG_ARGS)

        if platform == 'win32':
            if not self._platforms.is_win32_active or not cocos.os_is_win32:
                raise cocos.CCPluginError(
                    MultiLanguage.get_string('COMPILE_ERROR_BUILD_ON_WIN'),
                    cocos.CCPluginError.ERROR_WRONG_ARGS)

        if platform == 'linux':
            if not self._platforms.is_linux_active():
                raise cocos.CCPluginError("Please build on linux")
Esempio n. 41
0
    def run(self):
        package_path = self._package_path
        if os.path.isdir(package_path):
            raise cocos.CCPluginError(MultiLanguage.get_string('PACKAGE_PATH_EXISTED_FMT', package_path),
                                      cocos.CCPluginError.ERROR_PATH_NOT_FOUND)
        os.makedirs(package_path)

        self._vars["__PACKAGE_NAME__"] = self._package_name
        self.generate_uuid_string()

        template_path = get_template_path()

        self.copy_files_from_template(template_path, package_path)
Esempio n. 42
0
def _check_python_version():
    major_ver = sys.version_info[0]
    minor_ver = sys.version_info[1]
    ret = True
    if major_ver != 2:
        ret = False
    elif minor_ver < 7:
        ret = False

    if not ret:
        print(MultiLanguage.get_string('COCOS_PYTHON_VERSION_TIP_FMT') % (major_ver, minor_ver))

    return ret
Esempio n. 43
0
    def compile_for_win32(self):
        win32_output_dir = os.path.join(self.simulator_output_dir, "win32")
        win32_output_dir = self.convert_path_to_win32(win32_output_dir)
        if not os.path.isdir(win32_output_dir):
            os.makedirs(win32_output_dir)

        lang_file_path = os.path.join(
            self.simulator_abs_path,
            "frameworks/runtime-src/Classes/ide-support/lang")
        lang_copy_command = "xcopy /Y %s %s" % (
            self.convert_path_to_win32(lang_file_path), win32_output_dir)

        # get the vs version should be used
        if self.vs_version is None:
            ver_param = ''
        else:
            ver_param = '--vs %d' % self.vs_version

        env_param = utils.ExtendEnv.get_extend_env_str()
        if self.mode == 'debug':
            win32_src_dir = os.path.join(self.simulator_abs_path,
                                         "runtime/win32/")
            win32_src_dir = self.convert_path_to_win32(win32_src_dir)
            win32_dll_dir = self.convert_path_to_win32(
                os.path.join(os.path.dirname(self.cur_dir), "dll/"))
            cocos_cmd = " %s compile -p win32 -m debug --no-res --compile-script 0 %s" % (
                self.cocos_bin, ver_param)
            if env_param and len(env_param) > 0:
                cocos_cmd += (' --env "%s"' % env_param)

            command = ' '.join([
                cocos_cmd,
                " && xcopy /Y %s*.dll %s" % (win32_src_dir, win32_output_dir),
                " && xcopy /Y %s*.exe %s" % (win32_src_dir, win32_output_dir),
                " && %s" % (lang_copy_command),
                " && if exist %s*.dll xcopy /Y %s*.dll %s" %
                (win32_dll_dir, win32_dll_dir, win32_output_dir)
            ])
        else:
            cocos_cmd = " %s compile -p win32 -m release --no-res --compile-script 0 -o %s %s" % (
                self.cocos_bin, win32_output_dir, ver_param)
            if env_param and len(env_param) > 0:
                cocos_cmd += (' --env "%s"' % env_param)
            command = ' '.join([
                cocos_cmd,
                " && %s" % (lang_copy_command),
            ])

        self._run_cmd(command, self.simulator_abs_path)
        self.build_log += MultiLanguage.get_string('GEN_SIM_BUILD_SUCCESS_FMT',
                                                   ('Win32', self.mode))
Esempio n. 44
0
    def _create_from_cmd(self):
        # check the dst project dir exists
        if os.path.exists(self._projdir):
            message = MultiLanguage.get_string('NEW_ERROR_FOLDER_EXISTED_FMT',
                                               self._projdir)
            raise cocos.CCPluginError(message,
                                      cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        tp_dir = self._templates.template_path()

        creator = TPCreator(self._lang, self._cocosroot, self._projname,
                            self._projdir, self._tpname, tp_dir, self._package,
                            self._mac_bundleid, self._ios_bundleid)
        # do the default creating step
        creator.do_default_step()

        data = None
        cfg_path = os.path.join(self._projdir, cocos_project.Project.CONFIG)
        if os.path.isfile(cfg_path):
            f = open(cfg_path)
            data = json.load(f)
            f.close()

        if data is None:
            data = {}

        if cocos_project.Project.KEY_PROJ_TYPE not in data:
            data[cocos_project.Project.KEY_PROJ_TYPE] = self._lang

        # script project may add native support
        if self._lang in (cocos_project.Project.LUA, cocos_project.Project.JS):
            if not self._other_opts.no_native:
                creator.do_other_step('do_add_native_support')
                data[cocos_project.Project.KEY_HAS_NATIVE] = True
            else:
                data[cocos_project.Project.KEY_HAS_NATIVE] = False

        # record the engine version if not predefined
        if not data.has_key(CCPluginNew.PROJ_CFG_KEY_ENGINE_VERSION):
            engine_version = get_engine_version(self._cocosroot)
            if engine_version is not None:
                data[CCPluginNew.PROJ_CFG_KEY_ENGINE_VERSION] = engine_version

        # if --portrait is specified, change the orientation
        if self._other_opts.portrait:
            creator.do_other_step("change_orientation",
                                  not_existed_error=False)

        # write config files
        with open(cfg_path, 'w') as outfile:
            json.dump(data, outfile, sort_keys=True, indent=4)
Esempio n. 45
0
    def update_project(self, android_platform):
        # Android SDK removed android command & ant support from SDK tools 25.3.0
        # So, we should check the Android SDK tools version
        sdk_tools_folder = os.path.join(self.sdk_root, 'tools')
        main_ver, minor_ver = self._get_android_sdk_tools_ver(sdk_tools_folder)
        no_ant = False
        if main_ver > 25 or (main_ver == 25 and minor_ver >= 3):
            no_ant = True

        if not self.use_studio and no_ant:
            # Tip the message that ant is not supported from Android SDK tools 25.3.0
            raise cocos.CCPluginError(
                MultiLanguage.get_string('COMPILE_ERROR_ANT_NOT_SUPPORTED'),
                cocos.CCPluginError.ERROR_OTHERS)

        if self.use_studio:
            manifest_path = os.path.join(self.app_android_root, 'app')
        else:
            manifest_path = self.app_android_root

        # check the android platform
        target_str = self.check_android_platform(self.sdk_root,
                                                 android_platform,
                                                 manifest_path)

        if no_ant:
            # should manually update the project
            self._write_local_properties(manifest_path)
            self._update_project_properties(manifest_path, target_str)
        else:
            # update project
            sdk_tool_path = os.path.join(sdk_tools_folder, "android")
            command = "%s update project -t %s -p %s" % (
                cocos.CMDRunner.convert_path_to_cmd(sdk_tool_path), target_str,
                manifest_path)
            self._run_cmd(command)

            # update lib-projects
            self.update_lib_projects(self.sdk_root, sdk_tool_path,
                                     android_platform, manifest_path)

        if self.use_studio:
            # copy the local.properties to the app_android_root
            file_name = 'local.properties'
            src_path = os.path.normpath(os.path.join(manifest_path, file_name))
            dst_path = os.path.normpath(
                os.path.join(self.app_android_root, file_name))
            if src_path != dst_path:
                if os.path.isfile(dst_path):
                    os.remove(dst_path)
                shutil.copy(src_path, dst_path)
Esempio n. 46
0
    def do_add_header_lib_on_win(self, source, tag):
        workdir, proj_file_path, lines = self.load_proj_win32()
        contents = []
        tag_found = False
        for line in lines:
            match = re.search(tag, line)
            if match is None:
                contents.append(line)
            else:
                includes = re.split(';', match.group(2))
                headers = []
                for include in includes:
                    include = self.get_win32_path(workdir, include)
                    if include is not None:
                        headers.append(include)

                str_to_add = self.get_win32_path(workdir, source)
                headers.append(str_to_add)
                headers = list(set(headers))
                start, end = match.span(0)
                parts = []
                parts.append(line[:start])
                parts.append(match.group(1))
                parts.append(';')
                for header in headers:
                    if header.find(' ') != -1:
                        header = '"' + header + '"'
                    parts.append(header)
                    parts.append(';')
                parts.append(match.group(3))
                parts.append(line[end:])
                contents.append(''.join(parts))
                tag_found = True

        if tag_found == False:
            raise cocos.CCPluginError(
                MultiLanguage.get_string('PACKAGE_TAG_NOT_FOUND_FMT',
                                         ("header", "win32")),
                cocos.CCPluginError.ERROR_PARSE_FILE)
        else:
            uninst_info = {
                'file': proj_file_path,
                'tags': [tag],
                'type': "lib",
                'platform': "win",
                'workdir': workdir,
                'string': str_to_add
            }
            self.append_uninstall_info(uninst_info)
            self.update_file_content(proj_file_path, contents, True)
    def _get_android_sdk_tools_ver(self, sdk_tools_path):
        cfg_file = os.path.join(sdk_tools_path, 'source.properties')

        if os.path.isfile(cfg_file):
            f = open(cfg_file)
            lines = f.readlines()
            pattern = r'^Pkg\.Revision=(\d+)\.(\d+)'
            for l in lines:
                match = re.match(pattern, l.strip())
                if match:
                    return ((int)(match.group(1)), (int)(match.group(2)))

        raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_UNKNOWN_ANDROID_SDK_TOOLS_VERSION'),
                                  cocos.CCPluginError.ERROR_PATH_NOT_FOUND)
Esempio n. 48
0
    def get_api_level(self, target_str, raise_error=True):
        match = re.match(r'android-(\d+)', target_str)
        if match is not None:
            ret = int(match.group(1))
        else:
            if raise_error:
                raise cocos.CCPluginError(
                    MultiLanguage.get_string('COMPILE_ERROR_NOT_VALID_AP_FMT',
                                             target_str),
                    cocos.CCPluginError.ERROR_PARSE_FILE)
            else:
                ret = -1

        return ret
Esempio n. 49
0
    def get_target_config(self, proj_path):
        property_file = os.path.join(proj_path, "project.properties")
        if not os.path.isfile(property_file):
            raise cocos.CCPluginError(
                MultiLanguage.get_string('COMPILE_ERROR_FILE_NOT_FOUND_FMT',
                                         property_file),
                cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        patten = re.compile(r'^target=(.+)')
        for line in open(property_file):
            str1 = line.replace(' ', '')
            str2 = str1.replace('\t', '')
            match = patten.match(str2)
            if match is not None:
                target = match.group(1)
                target_num = self.get_api_level(target)
                if target_num > 0:
                    return target_num

        raise cocos.CCPluginError(
            MultiLanguage.get_string('COMPILE_ERROR_TARGET_NOT_FOUND_FMT',
                                     property_file),
            cocos.CCPluginError.ERROR_PARSE_FILE)
Esempio n. 50
0
    def show_stat_agreement(cls, skip_agree_value=None):
        if cls.is_agreement_shown():
            return

        if skip_agree_value is None:
            # show the agreement
            input_value = raw_input(
                MultiLanguage.get_string('COCOS_AGREEMENT'))
            agreed = (input_value.lower() != 'n'
                      and input_value.lower() != 'no')
        else:
            # --agreement is used to skip the input
            agreed = skip_agree_value
        cls.change_agree_stat(agreed)
Esempio n. 51
0
    def rollback_files(self, files):
        for f in files:
            full_path = os.path.abspath(f)
            backup_file_path = '%s.bak' % full_path
            if not os.path.isfile(backup_file_path):
                continue

            try:
                shutil.copyfile(backup_file_path, full_path)
                os.remove(backup_file_path)
            except:
                Logging.warning(MultiLanguage.get_string('GEN_SIM_ROLL_BACK_FAIL_FMT',
                                                         (full_path, backup_file_path, full_path)))
                pass
Esempio n. 52
0
    def cp_self(self, project_dir, exclude_files):
        cocos.Logging.info(
            MultiLanguage.get_string('NEW_INFO_STEP_COPY_TEMPLATE_FMT',
                                     project_dir))

        if not os.path.exists(self.project_dir):
            os.makedirs(self.project_dir)

        copy_cfg = {
            "from": self.tp_dir,
            "to": self.project_dir,
            "exclude": exclude_files
        }
        cocos.copy_files_with_config(copy_cfg, self.tp_dir, self.project_dir)
Esempio n. 53
0
    def project_replace_project_name(self, v):
        """ will modify the content of the file
        """
        dst_project_dir = self.project_dir
        dst_project_name = self.project_name
        src_project_name = v['src_project_name']
        if dst_project_name == src_project_name:
            return

        cocos.Logging.info(
            MultiLanguage.get_string('NEW_INFO_STEP_REPLACE_PROJ_FMT',
                                     (src_project_name, dst_project_name)))
        files = v['files']
        for f in files:
            dst = f.replace("PROJECT_NAME", dst_project_name)
            if os.path.exists(os.path.join(dst_project_dir, dst)):
                replace_string(os.path.join(dst_project_dir, dst),
                               src_project_name, dst_project_name)
            else:
                cocos.Logging.warning(
                    MultiLanguage.get_string(
                        'NEW_WARNING_FILE_NOT_FOUND_FMT',
                        os.path.join(dst_project_dir, dst)))
Esempio n. 54
0
    def modify_files(self, v):
        """ will modify the content of the file
            format of v is :
            [
                {
                    "file_path": The path related with project directory,
                    "pattern": Find pattern,
                    "replace_string": Replaced string
                },
                ...
            ]
        """
        cocos.Logging.info(MultiLanguage.get_string('NEW_INFO_STEP_MODIFY_FILE'))
        for modify_info in v:
            modify_file = modify_info["file_path"]
            if not os.path.isabs(modify_file):
                modify_file = os.path.abspath(os.path.join(self.project_dir, modify_file))

            if not os.path.isfile(modify_file):
                cocos.Logging.warning(MultiLanguage.get_string('NEW_WARNING_NOT_A_FILE_FMT', modify_file))
                continue

            pattern = modify_info["pattern"]
            replace_str = modify_info["replace_string"]

            f = open(modify_file)
            lines = f.readlines()
            f.close()

            new_lines = []
            for line in lines:
                new_line = re.sub(pattern, replace_str, line)
                new_lines.append(new_line)

            f = open(modify_file, "w")
            f.writelines(new_lines)
            f.close()
Esempio n. 55
0
    def add_files_and_dir(self, command):
        backup_flag = command["backup_if_override"]
        package_name = self._package_name
        file_list = command["source"]
        src_dir = self._package_path + os.sep + command["src_dir"]
        dst_dir = self._project["path"] + os.sep + command["dst_dir"]

        for filename in file_list:
            src = src_dir + os.sep + filename
            dst = dst_dir + os.sep + filename

            if os.path.exists(dst):
                if backup_flag:
                    bak = dst + "_bak_by_" + package_name
                    if not os.path.exists(bak):
                        os.rename(dst, bak)
                        self.append_uninstall_info({
                            'bak_file': bak,
                            'ori_file': dst
                        })
                        self.save_uninstall_info()
                    else:
                        print MultiLanguage.get_string(
                            'PACKAGE_UNABLE_COPY_FMT', dst)
                        continue
                else:
                    if os.path.isdir(dst):
                        shutil.rmtree(dst)
                    else:
                        os.remove(dst)
            else:
                ensure_directory(os.path.dirname(dst))

            if os.path.isdir(src):
                shutil.copytree(src, dst)
            else:
                shutil.copy(src, dst)
Esempio n. 56
0
    def check_android_platform(self, sdk_root, android_platform, proj_path, auto_select):
        ret = android_platform
        min_platform = self.get_target_config(proj_path)
        if android_platform is None:
            # not specified platform, found one
            cocos.Logging.info(MultiLanguage.get_string('COMPILE_INFO_AUTO_SELECT_AP'))
            ret = self.select_default_android_platform(min_platform)
        else:
            # check whether it's larger than min_platform
            select_api_level = self.get_api_level(android_platform)
            if select_api_level < min_platform:
                if auto_select:
                    # select one for project
                    ret = self.select_default_android_platform(min_platform)
                else:
                    # raise error
                    raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_AP_TOO_LOW_FMT',
                                                                       (proj_path, min_platform, select_api_level)),
                                              cocos.CCPluginError.ERROR_WRONG_ARGS)

        if ret is None:
            raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_AP_NOT_FOUND_FMT',
                                                               (proj_path, min_platform)),
                                      cocos.CCPluginError.ERROR_PARSE_FILE)

        ret_path = os.path.join(cocos.CMDRunner.convert_path_to_python(sdk_root), "platforms", ret)
        if not os.path.isdir(ret_path):
            raise cocos.CCPluginError(MultiLanguage.get_string('COMPILE_ERROR_NO_AP_IN_SDK_FMT', ret),
                                      cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        special_platforms_info = {
            "android-4.2" : "android-17"
        }
        if special_platforms_info.has_key(ret):
            ret = special_platforms_info[ret]

        return ret
Esempio n. 57
0
    def _gather_sign_info(self):
        user_cfg = {}
        # get the path of keystore file
        while True:
            inputed = self._get_user_input(
                MultiLanguage.get_string('COMPILE_TIP_INPUT_KEYSTORE'))
            inputed = inputed.strip()
            if not os.path.isabs(inputed):
                if self.use_studio:
                    start_path = os.path.join(self.app_android_root, 'app')
                else:
                    start_path = self.app_android_root
                abs_path = os.path.join(start_path, inputed)
            else:
                abs_path = inputed

            if os.path.isfile(abs_path):
                user_cfg[self.key_store_str] = inputed.replace('\\', '/')
                break
            else:
                cocos.Logging.warning(
                    MultiLanguage.get_string('COMPILE_INFO_NOT_A_FILE'))

        # get the alias of keystore file
        user_cfg[self.key_alias_str] = self._get_user_input(
            MultiLanguage.get_string('COMPILE_TIP_INPUT_ALIAS'))

        # get the keystore password
        user_cfg[self.key_store_pass_str] = self._get_user_input(
            MultiLanguage.get_string('COMPILE_TIP_INPUT_KEY_PASS'))

        # get the alias password
        user_cfg[self.key_alias_pass_str] = self._get_user_input(
            MultiLanguage.get_string('COMPILE_TIP_INPUT_ALIAS_PASS'))

        # write the config into ant.properties
        self._write_sign_properties(user_cfg)
Esempio n. 58
0
    def _create_from_cmd(self):
        # check the dst project dir exists
        if os.path.exists(self._projdir):
            message = MultiLanguage.get_string('NEW_ERROR_FOLDER_EXISTED_FMT', self._projdir)
            raise cocos.CCPluginError(message, cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        creator = TPCreator(self._lang, self._cocosroot, self._projname, self._projdir,
                            self._tpname, self._tpdir, self._package, self._mac_bundleid, self._ios_bundleid)
        # do the default creating step
        creator.do_default_step()

        data = None
        cfg_path = os.path.join(self._projdir, cocos_project.Project.CONFIG)
        if os.path.isfile(cfg_path):
            f = open(cfg_path)
            data = json.load(f)
            f.close()

        if data is None:
            data = {}

        if cocos_project.Project.KEY_PROJ_TYPE not in data:
            data[cocos_project.Project.KEY_PROJ_TYPE] = self._lang

        # script project may add native support
        if self._lang in (cocos_project.Project.LUA, cocos_project.Project.JS):
            # REMOVE the option --no-native. Because it's added for Cocos Code IDE.
            # It will cause confusion: https://github.com/cocos2d/cocos2d-console/issues/401
            # if self._other_opts.no_native is not self._other_opts.no_native:
            #     creator.do_other_step('do_add_native_support')
            #     data[cocos_project.Project.KEY_HAS_NATIVE] = True
            # else:
            #     data[cocos_project.Project.KEY_HAS_NATIVE] = False
            creator.do_other_step('do_add_native_support')
            data[cocos_project.Project.KEY_HAS_NATIVE] = True

        # record the engine version if not predefined
        if not (cocos_project.Project.KEY_ENGINE_VERSION in data):
            engine_version = utils.get_engine_version(self._cocosroot)
            if engine_version is not None:
                data[cocos_project.Project.KEY_ENGINE_VERSION] = engine_version

        # if --portrait is specified, change the orientation
        if self._other_opts.portrait:
            creator.do_other_step("change_orientation", not_existed_error=False)

        # write config files
        with open(cfg_path, 'w') as outfile:
            json.dump(data, outfile, sort_keys=True, indent=4)
Esempio n. 59
0
    def parse_config(self):
        if not os.path.isfile(self.cfg_file_path):
            raise CCPluginError(
                MultiLanguage.get_string('GEN_LIBS_ERROR_WRONG_FILE_FMT',
                                         self.cfg_file_path),
                CCPluginError.ERROR_PATH_NOT_FOUND)

        try:
            f = open(self.cfg_file_path)
            self.cfg_info = json.load(f)
            f.close()
        except:
            raise CCPluginError(
                MultiLanguage.get_string('GEN_LIBS_ERROR_PARSE_FILE_FMT',
                                         self.cfg_file_path),
                CCPluginError.ERROR_PARSE_FILE)

        for k in LibsCompiler.CHECK_KEYS:
            if k not in self.cfg_info.keys():
                raise CCPluginError(
                    MultiLanguage.get_string(
                        'GEN_LIBS_ERROR_KEY_NOT_FOUND_FMT',
                        (k, self.cfg_file_path)),
                    CCPluginError.ERROR_WRONG_CONFIG)
Esempio n. 60
0
    def run(self, argv, dependencies):
        """
        """
        self.parse_args(argv)

        # create output directory
        try:
            os.makedirs(self._dst_dir)
        except OSError:
            if os.path.exists(self._dst_dir) == False:
                raise cocos.CCPluginError(
                    MultiLanguage.get_string(
                        'LUACOMPILE_ERROR_MKDIR_FAILED_FMT', self._dst_dir),
                    cocos.CCPluginError.ERROR_PATH_NOT_FOUND)

        # download the bin folder
        jsbcc_exe_path = os.path.join(self._workingdir, "bin", "jsbcc")
        if not os.path.exists(jsbcc_exe_path):
            download_cmd_path = os.path.join(self._workingdir, os.pardir,
                                             os.pardir)
            subprocess.call(
                "python %s -f -r no" %
                (os.path.join(download_cmd_path, "download-bin.py")),
                shell=True,
                cwd=download_cmd_path)

        # deep iterate the src directory
        for src_dir in self._src_dir_arr:
            self._current_src_dir = src_dir
            self._js_files[self._current_src_dir] = []
            self.deep_iterate_dir(src_dir)

        self.reorder_js_files()
        self.handle_all_js_files()
        cocos.Logging.info(
            MultiLanguage.get_string('LUACOMPILE_INFO_FINISHED'))