Exemple #1
0
def run_command(cmd, cwd=None, is_print=True, encrypt=None):
    if encrypt:
        cmd_str = ' '.join(cmd).replace(encrypt, "*******")
    else:
        cmd_str = ' '.join(cmd)
    if is_print:
        print('=================================================')
        print("========== [Run Command]: {} ==========".format(cmd_str))
        print('=================================================')
    process = subprocess.Popen(cmd,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT,
                               cwd=cwd)

    while True:
        out = process.stdout.read(1)
        if out == '' and process.poll() is not None:
            break
        if out != '':
            sys.stdout.write(out)
            sys.stdout.flush()

    exit_code = process.poll()
    if exit_code != 0:
        log_tool.show_error('Run Command Error for {}, Error code: {}'.format(
            cmd_str, exit_code))
        exit(exit_code)
    log_tool.show_info('Done!')
Exemple #2
0
def _PreHandle_plist():
    info_plist_path = os.path.join(IOS_PRJ_DIR, 'Info.plist')
    if (not os.path.isfile(info_plist_path)):
        log_tool.show_error("{} Can't Find!".format(info_plist_path))
        exit(1)

    plist_file = plistlib.readPlist(info_plist_path)

    # 配置AppId
    plist_file['CFBundleIdentifier'] = bundle_id
    # 配置版号
    plist_file['CFBundleShortVersionString'] = '{}.{}.{}'.format(MAJOR_NUMBER, MINOR_NUMBER, PATCH_NUMBER)
    plist_file['CFBundleVersion'] = BUILD_NUMBER
    # 配置显示名
    plist_file['CFBundleDisplayName'] = APP_SHOW_NAME

    # 配置描述文件
    if (SIGN_TYPE == 'Inhouse'):
        plist_file['method'] = 'enterprise'
    else:     
        if (PROFILE_TYPE == 'Development'):
            plist_file['method'] = 'development'
        else:
            plist_file['method'] = 'app-store'
    plist_file['provisioningProfiles'] = {bundle_id: provisioning_profile_specifier}

    # 此参数用来控制是否可以放至debug.ini
    if VERSION_TYPE.lower() != 'release':
        plist_file['UIFileSharingEnabled'] = True
    else:
        if 'UIFileSharingEnabled' in plist_file:
            del plist_file['UIFileSharingEnabled']

    plistlib.writePlist(plist_file, info_plist_path)
Exemple #3
0
def run_command_write_result_to_file(cmd,
                                     result_file,
                                     is_print=True,
                                     cwd=None):
    if is_print:
        print '================================================='
        print "========== [Run Command]: {} ==========".format(' '.join(cmd))
        print '================================================='
        print "========== [Result file]: {} ==========".format(result_file)
        print '================================================='

    with open(result_file, 'w') as outfile:
        process = subprocess.Popen(cmd,
                                   stdout=outfile,
                                   stderr=outfile,
                                   cwd=cwd)
        process.wait()

    exit_code = process.poll()
    if exit_code != 0:
        time.sleep(2)
        log_tool.show_error(
            '[ERROR]: Run Command Error for {}, Error code: {}'.format(
                ' '.join(cmd), exit_code))
        exit(exit_code)
    log_tool.show_info('Run Command is done!')
Exemple #4
0
def ExportIosPrj():
    build_function = 'KGame.KAutoBuilderProject.BuildiOS{}'.format(VERSION_TYPE)

    # 构造unity命令行参数
    build_params = []
    build_params.append('-majorNumber={}'.format(MAJOR_NUMBER))
    build_params.append('-minorNumber={}'.format(MINOR_NUMBER))
    build_params.append('-patchNumber={}'.format(PATCH_NUMBER))
    build_params.append('-buildNumber={}'.format(BUILD_NUMBER))
    build_params.append('-branchName={}'.format(BRANCH_NAME))
    build_params.append('-language={}'.format(LANGUAGE))
    build_params.append('-isObbVersion={}'.format(IS_OBB_VERSION))
    build_params.append('-needDownloadObb={}'.format(NEED_DOWNLOAD_OBB))
    build_params.append('-isProduct={}'.format(IS_PRODUCT))
    
    log_path = os.path.join(workspace.unity_project_path, "unity_build_ios_ipa_log.txt")
    unity_tool.build_with_params(build_function,
                                 UNITY_PATH,
                                 workspace.unity_project_path,
                                 log_path,
                                 build_params)

    if (not os.path.isfile(IOS_PRJ_PATH)):
        log_tool.show_error("Can't find the XCode project file {}!".format(IOS_PRJ_PATH))
        log_tool.show_error("ExportIosPrj Failed!")
        exit(1)
Exemple #5
0
    def get_update_package_setting(self):
        if not self.update_package_setting:
            try:
                setting_path = os.path.join(
                    self.unity_project_path,
                    'Setting/Base/Update/UpdatePackageSetting.txt')
                tabfile = TabFile(setting_path)
                if not tabfile.init():
                    log_tool.show_error('Load UpatePackageSetting.txt Failed')
                    return None

                self.update_package_setting = {}
                row_count = tabfile.get_row_count()
                for row in range(1, row_count + 1):
                    package_dir_name = tabfile.get_value(
                        row, 'PackageDirName').replace('\\', '/')
                    pack_dir_name = tabfile.get_value(row,
                                                      'PackDirName').replace(
                                                          '\\', '/')
                    bundle_dir_name = tabfile.get_value(
                        row, 'BundleDirName').replace('\\', '/')
                    bundle_file_name = tabfile.get_value(
                        row, 'BundleFileName').replace('\\', '/')
                    include_bundle_manifest = tabfile.get_value(
                        row, 'IncludeBundleManifest') == '1'
                    need_buildin = tabfile.get_value(row, 'NeedBuildIn') == '1'

                    if self.update_package_setting.has_key(package_dir_name):
                        update_package_setting = self.update_package_setting[
                            package_dir_name]
                    else:
                        update_package_setting = UpdatePackageSetting(
                            package_dir_name)
                        self.update_package_setting[
                            package_dir_name] = update_package_setting

                    if pack_dir_name != '':
                        update_package_setting.pack_dirs.append(pack_dir_name)

                    if bundle_dir_name != '':
                        update_package_setting.bundle_dirs.append(
                            bundle_dir_name)

                    if bundle_file_name != '':
                        update_package_setting.bundle_files.append(
                            bundle_file_name)

                    update_package_setting.include_bundle_manifest = update_package_setting.include_bundle_manifest or include_bundle_manifest
                    update_package_setting.need_buildin = update_package_setting.need_buildin or need_buildin

            except Exception as e:
                log_tool.show_error(
                    'GetUpdatePackageSetting Failed! Error: {}'.format(e))
                self.update_package_setting = None

        return self.update_package_setting
def DeleteUpdatePackage(pack_dir):
    hot_package_dir = _GetHotPackageDir()
    hot_package_dir = os.path.join(hot_package_dir, pack_dir)
    if not os.path.isdir(hot_package_dir):
        log_tool.show_info('HotPackageDir {} not Exist!'.format(hot_package_dir))
        return

    # 获取最新版本号
    resource_version_path = os.path.join(hot_package_dir, '{}.{}.resource_version.txt'.format(PACKAGE_NAME_PREFIX, MAIN_VERSION))
    last_version_number = _GetLastVersionNumber(resource_version_path)
    if last_version_number == 0:
        log_tool.show_info('last_version_number = {}, no update_version to delete!'.format(last_version_number))
        return

    global DELETE_VERSION_NUMBER
    if DELETE_VERSION_NUMBER == -1:
        DELETE_VERSION_NUMBER = last_version_number
    if DELETE_VERSION_NUMBER > last_version_number:
        log_tool.show_error('DELETE_VERSION_NUMBER {} > last_version_number {}', DELETE_VERSION_NUMBER, last_version_number)
        return
    
    delete_package_list = Queue.Queue()

    delete_version_number = last_version_number
    while delete_version_number >= DELETE_VERSION_NUMBER:
        for i in range(0, delete_version_number):
            zipfile_name = '{}.{}.{}-{}.zip'.format(PACKAGE_NAME_PREFIX, MAIN_VERSION, i, delete_version_number)
            zipfile_path = os.path.join(hot_package_dir, zipfile_name)
            zipfile_md5_path = '{}.md5'.format(zipfile_path)
            zipfile_info_path = '{}.info'.format(zipfile_path)

            if os.path.isfile(zipfile_path):
                delete_package_list.put(zipfile_path)
            if os.path.isfile(zipfile_md5_path):
                delete_package_list.put(zipfile_md5_path)
            if os.path.isfile(zipfile_info_path):
                delete_package_list.put(zipfile_info_path)

        version_zipfile_manifest_path = os.path.join(hot_package_dir, '{}.{}.{}.zip.manifest'.format(PACKAGE_NAME_PREFIX, MAIN_VERSION, delete_version_number))
        version_zipfile_info_path = os.path.join(hot_package_dir, '{}.{}.{}.zip.info'.format(PACKAGE_NAME_PREFIX, MAIN_VERSION, delete_version_number))
        if os.path.isfile(version_zipfile_manifest_path):
            delete_package_list.put(version_zipfile_manifest_path)
        if os.path.isfile(version_zipfile_info_path):
            delete_package_list.put(version_zipfile_info_path)

        delete_version_number = delete_version_number - 1

    # 删除热更版本文件
    while not delete_package_list.empty():
        source_file_path = delete_package_list.get()
        os.remove(source_file_path)

    # 更新热更版本号
    _SetLastVersionNumber(resource_version_path, DELETE_VERSION_NUMBER - 1)

    log_tool.show_info('auto_delete_update_package Done!')
Exemple #7
0
def BuildAndroidPrj():
    gradle_dir = os.path.join(
        workspace.unity_project_path,
        'AndroidPrj/Version_{}/{}'.format(LANGUAGE, PRODUCT_NAME))
    os.chdir(gradle_dir)

    # 删除Build目录
    build_dir = os.path.join(gradle_dir, 'build')
    if os.path.isdir(build_dir):
        shutil.rmtree(build_dir, ignore_errors=True)

    if VERSION_TYPE == 'Alpha':
        compile_parm = 'assembleDebug'
        dir_name = 'debug'
    elif VERSION_TYPE == 'Preview' or VERSION_TYPE == 'Release':
        compile_parm = 'assembleRelease'
        dir_name = 'release'
    else:
        compile_parm = None
        exit(1)

    if common.is_windows():
        cmd = ['gradlew', compile_parm]
        os.system(' '.join(cmd))
    else:
        chmod = ['chmod', '755', 'gradlew']
        common.run_command(chmod)

        cmd = ['./gradlew', compile_parm]
        common.run_command(cmd)

    apk_src_path = os.path.join(
        build_dir, 'outputs/apk/{}/{}-{}.apk'.format(dir_name, PRODUCT_NAME,
                                                     dir_name))

    # 检测Apk是否Build成功
    if not os.path.isfile(apk_src_path):
        log_tool.show_error(
            "Build Android Apk Failed! Can't Find the file: {}".format(
                apk_src_path))
        exit(1)

    # Apk改名
    build_date = time.strftime("%Y.%m.%d.%H.%M.%S", time.localtime())
    apk_dst_path = os.path.join(
        build_dir, 'outputs/apk/{}/{}_{}_{}.{}.{}.{}_{}_{}.apk'.format(
            dir_name, PRODUCT_NAME, BRANCH_NAME, MAJOR_NUMBER, MINOR_NUMBER,
            PATCH_NUMBER, BUILD_NUMBER, VERSION_TYPE, build_date))
    os.rename(apk_src_path, apk_dst_path)

    # 拷贝到Apk目录去
    apk_dir = GetApkDir()
    shutil.copy(apk_dst_path, apk_dir)
Exemple #8
0
	def init(self):
		try:
			file_handle = open(self.read_file_path, 'r')
			file_content = file_handle.readlines()

			self.file_head = file_content[0].rstrip('\r').rstrip('\n').split('\t')
			self.row_count = len(file_content) - 1
			self.col_count = len(self.file_head)

			self.data = []
			for row_content in file_content:
				content = row_content.rstrip('\r').rstrip('\n').split('\t')
				self.data.append(content)

			file_handle.close()
			return True
		except Exception as e:
			log_tool.show_error('Read file: {} failed! Error: {}'.format(self.read_file_path, e))
			return False
Exemple #9
0
def BuildIpa():
    if not common.is_macos():
        log_tool.show_error('Only mac can build ios ipa')
        exit(1)

    # if LOCAL_OP is False:
    #     UpdateProduct()

    #  清除上次构建残留
    ClearBuildInfo()

    # 删除不需要打包的资源
    ClearResNoNeedBuild()

    # 导出Ios工程
    ExportIosPrj()

    # # 分析日志行,确保unity是否构建成功
    # time.sleep(1)
    # log_path = os.path.join(workspace.unity_project_path, "unity_build_ios_ipa_log.txt")
    # if os.path.isfile(log_path):
    #     for line in fileinput.input(log_path, 1024):
    #         if "is an incorrect path for a scene file" in line:
    #             log_tool.show_error(u'[ERROR]: 场景文件路径不正确,请检查EditorBuildSettings')
    #             fileinput.close()
    #             exit(1)
    #         if "Compilation failed:" in line:
    #             log_tool.show_error('Build iOS Ipa Failed!')
    #             fileinput.close()
    #             exit(1)

    # Ios工程编译前处理
    PreHandleIosPrj()

    if ONLY_EXPORT is True:
        log_tool.show_info('Only Export XcodeProject, Excape BuildIosPrj!')
        exit(0)

    # 编译Ios工程,生成ipa
    BuildIosPrj()
Exemple #10
0
    def get_pack_setting(self):
        if not self.pack_setting:
            try:
                setting_path = os.path.join(
                    self.unity_project_path,
                    'Setting/Base/Update/PackSetting.txt')
                tabfile = TabFile(setting_path)
                if not tabfile.init():
                    log_tool.show_error('Load PackSetting.txt Failed')
                    return None

                self.pack_setting = {}
                row_count = tabfile.get_row_count()
                for row in range(1, row_count + 1):
                    pack_dir_name = tabfile.get_value(row,
                                                      'PackDirName').replace(
                                                          '\\', '/')
                    folder_path = tabfile.get_value(row, 'Folder').replace(
                        '\\', '/')
                    file_path = tabfile.get_value(row,
                                                  'File').replace('\\', '/')

                    if self.pack_setting.has_key(pack_dir_name):
                        pack_setting = self.pack_setting[pack_dir_name]
                    else:
                        pack_setting = PackSetting(pack_dir_name)
                        self.pack_setting[pack_dir_name] = pack_setting

                    if folder_path != '':
                        pack_setting.folders.append(folder_path)
                    if file_path != '':
                        pack_setting.files.append(file_path)

            except Exception as e:
                log_tool.show_error(
                    'GetPackSetting Failed! Error: {}'.format(e))
                self.pack_setting = None

        return self.pack_setting
def BuildAssetBundle():
    # 先更新到最新
    if LOCAL_OP is False:
        UpdateProduct()

    log_tool.show_info('[REBUILD] --> {}'.format(IS_REBUILD))
    ab_path = os.path.join(workspace.unity_project_path, 'Bundles')
    platform_bundle_path = os.path.join(ab_path, PLATFORM)

    if IS_REBUILD is True:
        # 如果是Rebuild,需要删除库里的Bundles目录
        log_tool.show_info('[AutoBuild] Rebuild AssetBundle, Delete Bundle Direcotory for {}'.format(PLATFORM))
        if os.path.isdir(platform_bundle_path):
            if LOCAL_OP is False:
                git_tool.git_delete(workspace.product_path, platform_bundle_path)
                git_tool.git_commit(workspace.product_path, '[AutoBuild] Rebuild AssetBundle, Delete Bundle Direcotory for {}'.format(PLATFORM))
            else:
                shutil.rmtree(platform_bundle_path)

        build_function = 'KGame.KAutoBuilderAB.ReBuildAssetBundles{}'.format(PLATFORM)
    else:
        build_function = 'KGame.KAutoBuilderAB.BuildAssetBundles{}'.format(PLATFORM)

    log_path = os.path.join(workspace.unity_project_path, "build_ab_log.txt")
    unity_tool.build(build_function, UNITY_PATH, workspace.unity_project_path, log_path)

    # 判断平台manifest文件是否存在,是则构建成功,否则失败
    if PLATFORM == 'Android':
        android_manifest_file = os.path.join(workspace.unity_project_path, 'Bundles/Android/Android.manifest')
        if not os.path.exists(android_manifest_file):
            log_tool.show_error("Build failed! Can't find the file of {}, Platform: {}".format(android_manifest_file, PLATFORM))
            exit(1)
    elif PLATFORM == 'iOS':
        ios_manifest_file = os.path.join(workspace.unity_project_path, 'Bundles/iOS/iOS.manifest')
        if not os.path.exists(ios_manifest_file):
            log_tool.show_error("Build failed! Can't find the file of {}, Platform: {}".format(ios_manifest_file, PLATFORM))
            exit(1)
    else:
        pass

    if not os.path.isdir(platform_bundle_path):
        log_tool.show_error("Can't find the path of {}".format(platform_bundle_path))
        exit(1)

    # 提交AB相关修改文件
    if LOCAL_OP is False:
        ab_setting_path = os.path.join(workspace.unity_project_path, 'Setting/Base/FileAbInfoSetting_{}.txt'.format(PLATFORM))
        git_tool.git_add(workspace.product_path, ab_setting_path)
        git_tool.git_add(workspace.product_path, platform_bundle_path)
        git_tool.git_commit(workspace.product_path, '[AutoBuild]: Asset Bundles Rebuild: {} Commit.'.format(IS_REBUILD))
Exemple #12
0
def _PreHandleIosPrj_Sign(xcode_project):
    global developmentTeam
    global code_sign_identity
    global provisioning_profile_specifier
    global bundle_id

    if SIGN_TYPE == 'Inhouse':
        if PROFILE_TYPE == 'Development':
            # 暂时没有development类型的pp
            log_tool.show_error('Have not Inhouse Development Provioning Profile')
            exit(1)
        elif PROFILE_TYPE == 'Distribution':
            developmentTeam = globalvalue_tool.get_value("development_team_inhouse")
            code_sign_identity = globalvalue_tool.get_value("code_sign_identity_inhouse_distribution")
            provisioning_profile_specifier = globalvalue_tool.get_value("provisioning_profile_specifier_inhouse_distribuion")
            bundle_id = globalvalue_tool.get_value("bundle_id_ios_inhouse")

    elif SIGN_TYPE == 'AppStore':
        if PROFILE_TYPE == 'Development':
            # 暂时没有development类型的pp
            log_tool.show_error('Have not AppStore Development Provioning Profile')
            exit(1)
        elif PROFILE_TYPE == 'Distribution':
            developmentTeam = globalvalue_tool.get_value("development_team_appstore")
            code_sign_identity = globalvalue_tool.get_value("code_sign_identity_appstore_distribution")
            provisioning_profile_specifier = globalvalue_tool.get_value("provisioning_profile_specifier_appstore_distribuion")
            bundle_id = globalvalue_tool.get_value("bundle_id_ios_appstore")

    else:
        log_tool.show_error("Invalid SignType {}".format(SIGN_TYPE))
        exit(1)

    # 设置手动签名
    xcode_project.set_flags('CODE_SIGN_STYLE', 'Manual')
    for st in xcode_project.get_build_phases_by_name('PBXProject'):
        for t in xcode_project.get_build_phases_by_name('PBXNativeTarget'):
            log_tool.show_info("Handling target[{}], Set 'ProvisioningStyle = Manual'".format(t.name))
            st.set_provisioning_style('Manual', t)
            st.attributes.TargetAttributes[u'1D6058900D05DD3D006BFB54'].parse({'DevelopmentTeam': developmentTeam})
            st.attributes.TargetAttributes[u'1D6058900D05DD3D006BFB54'].SystemCapabilities.parse(
                {'com.apple.Push': {'enabled': '1'}})
            st.attributes.TargetAttributes[u'1D6058900D05DD3D006BFB54'].SystemCapabilities.parse(
                {'com.apple.Keychain': {'enabled': '0'}})

    xcode_project.set_flags('DEVELOPMENT_TEAM', developmentTeam, target_name='Unity-iPhone')
    xcode_project.set_flags('CODE_SIGN_IDENTITY', code_sign_identity)
    xcode_project.set_flags('CODE_SIGN_IDENTITY[sdk=iphoneos*]', code_sign_identity)
    xcode_project.set_flags('PROVISIONING_PROFILE_SPECIFIER', provisioning_profile_specifier, target_name='Unity-iPhone')
def get_value(value_name):
    try:
        return globalvalue[value_name]
    except Exception as e:
        log_tool.show_error('GlobalValue {} not Exist!'.format(value_name))
        return None
def ProducePackage():
    if not PACK_DIR or PACK_DIR == '':
        log_tool.show_error("PACK_DIR is none!")
        return

    ProduceUploadPackage(PACK_DIR)
def DeletePackage():
    if not PACK_DIR or PACK_DIR == '':
        log_tool.show_error("PACK_DIR is none!")
        return

    DeleteUpdatePackage(PACK_DIR)
def ProduceUploadPackage(pack_dir):
    temp_dir = _GetTempDir()
    if os.path.isdir(temp_dir):
        shutil.rmtree(temp_dir)

    hot_package_dir = _GetHotPackageDir()
    hot_package_dir = os.path.join(hot_package_dir, pack_dir)
    if not os.path.isdir(hot_package_dir):
        log_tool.show_error('HotPackageDir {} not Exist!'.format(hot_package_dir))
        return
    
    upload_package_list = Queue.Queue()

    # 拷贝resource_version
    resource_version_path = os.path.join(hot_package_dir, '{}.{}.resource_version.txt'.format(PACKAGE_NAME_PREFIX, MAIN_VERSION))
    upload_package_list.put(resource_version_path)

    global UPDATE_VERSION_NUMBER
    if UPDATE_VERSION_NUMBER == -1:
        UPDATE_VERSION_NUMBER = _GetLastVersionNumber(resource_version_path)

    for i in range(0, UPDATE_VERSION_NUMBER):
        if i == 0 or UPDATE_VERSION_NUMBER - i <= MAX_VERSION_SPAN:
            zipfile_name = '{}.{}.{}-{}.zip'.format(PACKAGE_NAME_PREFIX, MAIN_VERSION, i, UPDATE_VERSION_NUMBER)
            zipfile_path = os.path.join(hot_package_dir, zipfile_name)
            zipfile_md5_path = '{}.md5'.format(zipfile_path)
            zipfile_info_path = '{}.info'.format(zipfile_path)

            upload_package_list.put(zipfile_path)
            upload_package_list.put(zipfile_md5_path)
            upload_package_list.put(zipfile_info_path)

    temp_dir = _GetTempDir()
    branch_name = BRANCH_NAME if '/' not in BRANCH_NAME else BRANCH_NAME.replace('/', '_')
    copy_dir = os.path.join(temp_dir, '{}/{}/{}/{}'.format(branch_name, MAIN_VERSION, PLATFORM, pack_dir))
    if not os.path.isdir(copy_dir):
        os.makedirs(copy_dir)

    while not upload_package_list.empty():
        source_file_path = upload_package_list.get()
        target_file_path = os.path.join(copy_dir, os.path.basename(source_file_path))
        if os.path.isfile(source_file_path):
            log_tool.show_info('=================== Copy {} to {} ======================'.format(source_file_path, target_file_path))
            shutil.copyfile(source_file_path, target_file_path)
        else:
            log_tool.show_error("Can't find the file {}".format(source_file_path))
            return

    # zip file
    os.chdir(temp_dir)
    upload_package_zipfile = '{}.{}.{}-{}.zip'.format(PACKAGE_NAME_PREFIX, PLATFORM, MAIN_VERSION, UPDATE_VERSION_NUMBER)
    zip_cmd = ['zip', '-r', upload_package_zipfile, branch_name]
    common.run_command(zip_cmd)

    # 拷贝到热更包目录
    upload_dir = _GetUploadDir()
    upload_dir = os.path.join(upload_dir, pack_dir)
    if not os.path.isdir(upload_dir):
        os.makedirs(upload_dir)
        
    target_file_path = os.path.join(upload_dir, os.path.basename(upload_package_zipfile))
    shutil.copyfile(upload_package_zipfile, target_file_path)

    # 删除临时目录
    shutil.rmtree(temp_dir)

    log_tool.show_info('auto_build_upload_hotpackage Done!')
Exemple #17
0
def Pack(package_setting, is_packbase):
    # FilePacker path
    if common.is_windows():
        filepackerpath = os.path.join(workspace.unity_project_path, 'FilePacker.exe')
    else:
        filepackerpath = os.path.join(workspace.unity_project_path, 'FilePacker')
        # 获取执行权限
        os.chdir(workspace.unity_project_path)
        chmod = ['chmod', '755', 'FilePacker']
        common.run_command(chmod)

    UPDATER_PACK_PATH = os.path.join(CURRENT_PATH, 'updater_pack.py')
    UPDATER_CMD = ['python',
                   UPDATER_PACK_PATH,
                   BRANCH_NAME,
                   VERSION_NUMBER,
                   MAIN_VERSION,
                   PLATFORM,
                   workspace.unity_project_path,
                   PROJECT_NAME,
                   package_setting.package_dir_name,
                   '{}'.format(is_packbase),
                   IS_REBOOT,
                   IS_BACKGROUND_UPDATE]

    # 生成Patch包
    for pack_dir in package_setting.pack_dirs:
        pack_idx_path = os.path.join(workspace.unity_project_path, 'Assets/StreamingAssets/Res/{}/pack.idx'.format(pack_dir))
        pack_dat_path = os.path.join(workspace.unity_project_path, 'Assets/StreamingAssets/Res/{}/pack0.dat'.format(pack_dir))

        if not os.path.isfile(pack_idx_path) or not os.path.isfile(pack_dat_path):
            log_tool.show_error("Can't find {} and {}".format(pack_idx_path, pack_dat_path))
            exit(1)

        if not is_packbase:
            pack_settings = workspace.get_pack_setting()
            if not pack_settings:
                log_tool.show_error("GetPackSetting Failed")
                exit(1)

            if not pack_settings.has_key(pack_dir):
                log_tool.show_error('{} not in PackSetting'.format(pack_dir))
                exit(1)

            patch_srcfile_path = os.path.join(workspace.unity_project_path, 'Assets/StreamingAssets/Res/{}/pack.patch'.format(pack_dir))
            patch_path = os.path.join(workspace.unity_project_path, 'Patch/{}'.format(pack_dir))
            patch_idx_path = os.path.join(patch_path, 'pack.idx')
            patch_dstfile_path = os.path.join(patch_path, 'pack.patch')

            if os.path.isdir(patch_path):
                shutil.rmtree(patch_path)
            os.makedirs(patch_path)

            # 修改pack配置文件
            pack_ini_file = os.path.join(workspace.unity_project_path, 'FilePacker.ini')
            pack_setting = pack_settings[pack_dir]
            # outdir
            config_content = '[FilePacker]\n'
            config_content = '{}DstPath=Assets/StreamingAssets/Res/{}\n'.format(config_content, pack_dir)
            # folders
            folder_index = 1
            for folder in pack_setting.folders:
                config_content = '{}Folder{}={}\n'.format(config_content, folder_index, folder)
                folder_index = folder_index + 1
            # files
            file_index = 1
            for file in pack_setting.files:
                config_content = '{}File{}={}\n'.format(config_content, file_index, file)
                file_index = file_index + 1
            file = open(pack_ini_file, 'w')
            file.write(config_content)
            file.close()

            log_tool.show_info('Run FilePacker --patch')
            common.run_command([filepackerpath, '--patch'])
            log_tool.show_info('Run FilePacker --patch is done!')

            if os.path.isfile(pack_idx_path) and os.path.isfile(patch_srcfile_path):
                log_tool.show_info('Copy {} --> {}'.format(pack_idx_path, patch_idx_path))
                shutil.copyfile(pack_idx_path, patch_idx_path)
                log_tool.show_info('Copy {} --> {}'.format(patch_srcfile_path, patch_dstfile_path))
                shutil.copyfile(patch_srcfile_path, patch_dstfile_path)
            else:
                log_tool.show_info("Can't find {}! No Change!".format(patch_srcfile_path))

    # 生成热更包
    log_tool.show_info("========== Run updater_pack.py ==========")
    common.run_command(UPDATER_CMD)
Exemple #18
0
    update_version_info = {}
    for setting in update_package_setting.values():
        resource_version = '{}/{}/{}.resource_version.txt'.format(package_dir, setting.package_dir_name, package_name)
        strVersion = ''
        with open(resource_version, 'rb+') as f:
            strVersion = f.read()
        update_version_info[setting.package_dir_name] = int(strVersion)
    version_info['updateVersion'] = update_version_info

    # write file
    with open(version_file, 'w') as f:
        json.dump(version_info, f, indent=4, ensure_ascii=False)


if __name__ == '__main__':
    if LOCAL_OP is False:
        UpdateProduct()

    update_package_setting = workspace.get_update_package_setting()
    if not update_package_setting:
        log_tool.show_error('Get UpdatePackageSetting Failed!')
        exit(1)

    # 生成全部更新包
    for setting in update_package_setting.values():
        is_packbase = NeedBasePack(setting.package_dir_name)
        Pack(setting, is_packbase)

    # 生成版本信息文件
    CreateVersionInfo(update_package_setting)
def BuildPack():
    # 先更新到最新
    if LOCAL_OP is False:
        UpdateProduct()

    # 生成所有脚本路径的配置表
    # 现在不需要生成,可以通过加载目录的方式
    #CreateAllLuaFilePath()

    sleep(1)

    # 获取所有需要Pack的目录
    pack_settings = workspace.get_pack_setting()
    if not pack_settings:
        exit(1)

    # FilePacker path
    if common.is_windows():
        filepackercpath = os.path.join(workspace.unity_project_path, 'FilePacker.exe')
    elif common.is_macos():
        filepackercpath = os.path.join(workspace.unity_project_path, 'FilePacker')
        # 获取执行权限
        os.chdir(workspace.unity_project_path)
        chmod = ['chmod', '755', 'FilePacker']
        common.run_command(chmod)

    if not os.path.isfile(filepackercpath):
        log_tool.show_error("Can't find the FilePacker.exe: {}".format(filepackercpath))
        exit(1)


    # 需要打包的目录
    pack_dirs = []
    if not PACK_DIRS or PACK_DIRS == '':
        for setting in pack_settings.values():
            pack_dirs.append(setting.pack_dir_name)
    else:
        dirs = PACK_DIRS.split(',')
        for dir_name in dirs:
            pack_dirs.append(dir_name.strip())

    # 删除需要打包的目录
    root_dir = os.path.join(workspace.unity_project_path, 'Assets/StreamingAssets/Res')
    for pack_dir in pack_dirs:
        pack_forlder = os.path.join(root_dir, pack_dir)
        if os.path.isdir(pack_forlder):
            shutil.rmtree(pack_forlder)

    # 生成Pack文件
    pack_ini_file = os.path.join(workspace.unity_project_path, 'FilePacker.ini')
    for pack_dir in pack_dirs:
        # 修改pack配置文件
        if not pack_settings.has_key(pack_dir):
            log_tool.show_error('{} not in PackSetting'.format(pack_dir))
            exit(1)

        pack_setting = pack_settings[pack_dir]

        # outdir
        config_content = '[FilePacker]\n'
        config_content = '{}DstPath=Assets/StreamingAssets/Res/{}\n'.format(config_content, pack_dir)

        # folders
        folder_index = 1
        for folder in pack_setting.folders:
            config_content = '{}Folder{}={}\n'.format(config_content, folder_index, folder)
            folder_index = folder_index + 1

        # files
        file_index = 1
        for file in pack_setting.files:
            config_content = '{}File{}={}\n'.format(config_content, file_index, file)
            file_index = file_index + 1
        
        file = open(pack_ini_file, 'w')
        file.write(config_content)
        file.close()

        # 生成Pack目录
        dir_path = os.path.join(workspace.unity_project_path, 'Assets/StreamingAssets/Res/{}'.format(pack_dir))
        if not os.path.isdir(dir_path):
            os.makedirs(dir_path)

        common.run_command(filepackercpath)

    # 打开一下Unity,自动生成一下pack的meta文件
    if LOCAL_OP is False:
        log_tool.show_info('Wait For Generator MetaFiles')
        build_function = 'KGame.KAutoBuilderPack.GenerMetaFiles'
        log_path = os.path.join(workspace.unity_project_path, 'generator_pack_metafiles_log.txt')
        unity_tool.build(build_function, UNITY_PATH, workspace.unity_project_path, log_path)
        log_tool.show_info('Generator MetaFiles Finished')