python 自动化打包ios ipa

44 阅读3分钟

main.py 代码


# import os
# import subprocess #执行命令,就行在命令行里执行一样
import datetime
import plistlib
import re
import shutil
import subprocess
import time
import os
import requests

#参考 https://blog.csdn.net/Love_525/article/details/103823768

appName="xxx" #项目名称
proPath = "~/Desktop/xx"
archiveFolder = "/Users/xx/Desktop/xx"

# 蒲公英账号USER_KEY、API_KEY及App_Key 需要替换成自己的蒲公英账号对应的key
USER_KEY = "2b4abf321350691xxxxxxx"
API_KEY = "fe373d4a423439exxxxxxxx"

def  mainGo():
    ready()
    # uploadIPA()
    # getPgyerToken()

def ready():
    print("---- 准备 开始  -----")

    # 删除之前打包的 IPA文件夹
    subprocess.call(["rm", "-rf", f'{archiveFolder}/Archive/{appName}.xcarchive'])
    time.sleep(1)

    subprocess.call(["rm", "-rf", f'{archiveFolder}/iPa/{appName}.ipa'])
    time.sleep(1)


    removeOldArchiveCmd = f'rm -rf {archiveFolder}/Archive/{appName}.xcarchive'
    executeCmd(removeOldArchiveCmd)

    removeOldIpaCmd = f'rm -rf {archiveFolder}/iPa/{appName}.ipa'
    executeCmd(removeOldIpaCmd)

    # cdProjectPathCmd = f'cd {proPath}'
    # executeCmd(cdProjectPathCmd)

    print("---- 准备 结束  -----")
    clean()

def clean():
    print("---- clean 开始  -----")
    # 开始时间
    start = time.time()

    cleanProRun = f'xcodebuild clean -workspace {proPath}/{appName}.xcworkspace -scheme {appName} -configuration Debug'

    # executeCmd(cleamCmd)
    cleanProcessRun = subprocess.Popen(cleanProRun,shell=True)
    cleanProcessRun.wait()
    # 结束时间
    end = time.time()
    cleanReturnCode = cleanProcessRun.returncode

    print(f'----- clean return Code = {cleanReturnCode}')
    if cleanReturnCode != 0:
        print("\n*************** clean失败 ****** 耗时:%s秒 ***************\n" % (end - start))
    else:
        print("\n*************** clean成功 ********* 耗时:%s秒 ************\n" % (end - start))
        # archive
        archive()

def archive():
    print("---- 打包 开始  -----")
    # 开始时间
    start = time.time()

    archiveCmd = f'xcodebuild archive -workspace {proPath}/{appName}.xcworkspace -scheme {appName} -configuration Debug -archivePath {archiveFolder}/Archive/{appName}.xcarchive'
    # executeCmd(cmd)

    archiveProcessRun = subprocess.Popen(archiveCmd, shell=True)
    archiveProcessRun.wait()
    # 结束时间
    end = time.time()
    # 获取Code码
    archiveReturnCode = archiveProcessRun.returncode
    print('----- archive ReturnCode = %s' % archiveReturnCode)
    if archiveReturnCode != 0:
        print("\n***************  archive失败  ******  耗时:%s秒  ***************\n" % (end - start))
    else:
        print("\n***************  archive成功  *********  耗时:%s秒  ************\n" % (end - start))
        # 导出IPA
        exportIPA()


    # 切换到当前目录
    # os.chdir(backupIPA)

def exportIPA():
    print("---- 导出ipa 开始  -----")

    start = time.time()
    pathArchive = f'{archiveFolder}/Archive/{appName}.xcarchive'

    isExistArchive = os.path.exists(pathArchive)
    if isExistArchive == False:
        print(f'----- 不存在 archive 文件 = {pathArchive}')
        return

    exportCmd = f'xcodebuild -exportArchive -archivePath {archiveFolder}/Archive/{appName}.xcarchive -exportPath {archiveFolder}/iPa -exportOptionsPlist {archiveFolder}/exportOptionsPlist.plist -allowProvisioningUpdates'
    # executeCmd(cmd)
    exportProcessRun = subprocess.Popen(exportCmd, shell=True)
    exportProcessRun.wait()

    # 结束时间
    end = time.time()
    # 获取Code码
    exportReturnCode = exportProcessRun.returncode
    if exportReturnCode != 0:
        print("\n***************   导出IPA失败    *********耗时: %s秒  ************\n" % (end - start))
    else:
        print("\n***************   导出IPA成功      *********   耗时:%s秒  ************\n" % (end - start))
        uploadIPA()
        # 切换到当前目录
        # os.chdir(backupIPA)
        # # 删除app后缀文件
        # commands.getoutput('rm -rf ./*.xcarchive')
        # time.sleep(1)

#        uploadIPA('%s/%s.ipa'%(backupIPA,schemeName))
#        openDownloadUrl()



    print("---- 导出ipa 结束  -----")

def uploadIPA():
    print("---- 开始 上传到蒲公英 -----")
    start = time.time()

    IPAPath = f'{archiveFolder}/iPa/xx.ipa'

    isExistIpa = os.path.exists(IPAPath)
    if isExistIpa == False:
        print(f"\n--------------- 不存在 ipa 文件 ipaPath = {IPAPath}")
        return
    else:
        url = 'https://www.pgyer.com/apiv2/app/upload'
        data = {
            'userKey': USER_KEY,
            '_api_key': API_KEY
        }
        files = {'file': open(IPAPath, 'rb')}
        response = requests.post(url, data=data, files=files)
        statusCode = response.status_code
        responseText = response.text
        print(f'-------- 上传结束 statusCode = {statusCode},response = {responseText}')
        # 结束时间
        end = time.time()
        print("\n***************   上传结束    *********耗时: %s秒  ************\n" % (end - start))

def getPgyerToken():
    print("---- 开始 获取蒲公英token -----")
    start = time.time()
    url = "https://api.pgyer.com/apiv2/app/getCOSToken"

    param = {
        "_api_key" : API_KEY,
        "buildType": "ios"
    }
    reponse = requests.post(url, data=param)
    statusCode = reponse.status_code
    reponseText = reponse.text
    print(f'------ get token statusCode = {statusCode},reponseText = {reponseText}')
    if statusCode == 200:
        responseJson = reponse.json()
        responseData = responseJson['data']

        endPoint = responseData['endpoint']
        key = responseData['key']

        responseParams = responseData['params']
        signature = responseParams['signature']
        token = responseParams['x-cos-security-token']
        uploadIPAFile(endPoint,key,signature,token)

    else:
        # 结束时间
        end = time.time()
        print("\n***************   获取蒲公英token 结束    *********耗时: %s秒  ************\n" % (end - start))


def uploadIPAFile(endPoint,key, signature,token):
    print("---- 开始 快速 上传到蒲公英 -----")
    start = time.time()

    IPAPath = f'{archiveFolder}/iPa/BB语音.ipa'

    isExistIpa = os.path.exists(IPAPath)
    if isExistIpa == False:
        print(f"\n--------------- 不存在 ipa 文件 ipaPath = {IPAPath}")
        return
    else:
        url = 'https://www.pgyer.com/apiv2/app/upload'
        data = {
            'userKey': USER_KEY,
            '_api_key': API_KEY
        }
        files = {'file': open(IPAPath, 'rb')}
        response = requests.post(url, data=data, files=files)
        statusCode = response.status_code
        responseText = response.text
        print(f'-------- 上传结束 statusCode = {statusCode},response = {responseText}')
        # 结束时间
        end = time.time()
        print("\n***************   上传结束    *********耗时: %s秒  ************\n" % (end - start))

def print_hi(name):
    # 在下面的代码行中使用断点来调试脚本。
    print(name)
    print(f'Hi, {name}')  # 按 ⌘F8 切换断点。

def print2(name):
    print(f'hi2, {name}')


def executeCmd(cmd):
    """
    指定终端指令
    :param cmd: 指令字符串
    :return: 返回输出字符串, 判断是否报错
    """
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    output, stderrOutput = p.communicate()
    output = output.decode()
    print(f'cmd 命令 =, {cmd}')
    print(f'cmd 结果 =, {output}')
    resultCode = p.returncode
    return output, resultCode != 0


def dealPrintMsg(self, msg, status=1):
    """
    处理打印行为
    :param status: 状态
    :param msg: 打印信息
    :return: 无返回值
    """
    print("{状态: %s, 打印信息: %s}" % (str(status), msg))


# 按装订区域中的绿色按钮以运行脚本。
if __name__ == '__main__':
    # print_hi('PyCharm')
    mainGo()
# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助


#print_hi("PyCharm")