移动端还在手动打包吗?手把手教你基于 Python实现项目的自动打包与发布

引言

在移动应用的开发过程中,频繁的打包、上传以及通知相关成员是一个相对繁琐且耗时的过程。为了简化这一流程,我编写了一个 Python 脚本,能够自动化完成分支切换、打包 Android 和 iOS 应用、上传文件到腾讯云 COS 并推送到企业微信。本文将介绍该脚本的实现细节,希望能够对开发者朋友们有所帮助。

1. 脚本功能概述

该脚本的主要功能包括:

  1. 自动切换到指定的 Git 分支。
  2. 使用 flutter 命令打包 Android 和 iOS 应用。
  3. 将打包好的应用上传至腾讯云 COS。
  4. 通过企业微信 webhook 将上传成功的消息推送给相关人员。
    整个流程实现了打包与发布的全自动化,为开发者节省了大量时间,同时也避免了手动操作可能带来的失误。

2. 环境准备

2.1 依赖安装

在使用该脚本之前,请确保安装了以下依赖:

  1. Python:建议使用 Python 3.6 及以上版本。
  2. qcloud_cos:腾讯云 COS 的 Python SDK。 需要开通腾讯云服务
  3. Flutter SDK:确保 Flutter 环境已正确配置。
  4. Git:用于版本控制和分支管理。
  5. Android:根据需要自行配置。
  6. iOS:根据需要自行配置。

安装 qcloud_cos SDK:(python安装库的方法,也可以通过开发工具配置,需要一定python基础)

pip install qcloud_cos

2.2 配置环境变量

变量 含义
target_branch 仓库分支名
pushUrl 企业微信推送地址
Access_id 腾讯云 COS需要的参数
Access_key 腾讯云 COS需要的参数

在脚本中,我们使用了 CosConfig 腾讯云 COS来做包的服务器上传,使用企业微信机器人来推送到相关群。请在实际使用时结合公司自己的基建来灵活安排

3. 脚本实现详解

3.1 引入依赖和配置

首先,我们引入了脚本所需的 Python 模块,并进行了腾讯云 COS 的配置。

import datetime
from qcloud_cos import CosConfig, CosS3Client
import os
import subprocess
import threading
import time


pub_version = '1.0.0+1000000'
target_branch = "your_branch"


pushUrl = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=your_webhook_key'

client = CosS3Client(CosConfig(Region='your-region', Access_id='your-access-id', Access_key='your-access-key'))

3.2 切换分支

使用 subprocess 模块执行 Git 命令,实现自动切换到目标分支,并拉取最新代码:

def switch_to_branch():
    try:
        print("Switching to branch...")
        subprocess.run("git fetch --all", shell=True)
        print("git fetch --all...")
        subprocess.run(f"git checkout -f {target_branch}", shell=True)
        print("git checkout -f...")
        subprocess.run(f"git pull", shell=True)
        print("Pulling latest changes...")
        event.set()
    except Exception as e:
        print(f"Error in switch_to_branch: {e}")


switch_thread = threading.Thread(target=switch_to_branch)
switch_thread.start()
event.wait()

3.3 打包应用

使用 Flutter 的命令行工具打包 Android 和 iOS 应用。我们在 aliases 字典中定义了常用的打包命令,然后通过 subprocess 执行。请结合自己项目使用相关打包脚本即可。

def execute_command(command):
    aliases = {
        "pkr": "flutter build apk --no-tree-shake-icons",
        "pki": "flutter build ipa --no-tree-shake-icons --export-options-plist /path/to/your/export-options.plist"
    }
    subprocess.run("pwd", shell=True)
    command = aliases.get(command)
    if not command:
        return "Unknown command"
    print(f"Starting to execute command: {command}")
    start_time = time.time()
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    while True:
        output = process.stdout.readline()
        if output == b'' and process.poll() is not None:
            break
        if output:
            print(output.decode().strip())
    error_output = process.stderr.read()
    if error_output:
        print(error_output.decode().strip())
    end_time = time.time() 
    elapsed_time = end_time - start_time
    print(f"Command execution completed. Time taken: {elapsed_time:.2f} seconds")
    if command == aliases["pkr"]:
        uploadAppAndroid()
    if command == aliases["pki"]:
        uploadAppIOS()

3.4 上传应用到腾讯云 COS

通过 client.upload_file 将打包好的 APK 和 IPA 文件上传到腾讯云 COS。上传成功后,将文件的下载链接通过企业微信 webhook 推送给相关人员。

def uploadAppAndroid():
    parts = pub_version.split('+')
    version = parts[0]
    build = parts[1]
    now = datetime.datetime.now()
    timestamp = now.strftime("%Y%m%d%H%M")
    
    androidPath = f"https://your-cos-domain/ui/android/project/{version}/Publish_Market/{build}/v{version}-{timestamp}-redcity.apk"
    coskey = androidPath.split('https://your-cos-domain')[1]
    response = client.upload_file(
        Bucket='your-bucket-name',
        LocalFilePath='/path/to/your/apk/app-release.apk',
        Key=coskey, PartSize=10, MAXThread=10)
    print("market_url: " + response['Location'])
    sendWebhook(response['Location'], '安卓包', timestamp)

def uploadAppIOS():
    parts = pub_version.split('+')
    version = parts[0]
    build = parts[1]
    now = datetime.datetime.now()
    timestamp = now.strftime("%Y%m%d%H%M")
    
    iosPath = f"https://your-cos-domain/ui/android/project/{version}/Publish_Market/{build}/v{version}-{timestamp}-redcity.ipa"
    coskey = iosPath.split('https://your-cos-domain')[1]
    response = client.upload_file(
        Bucket='your-bucket-name',
        LocalFilePath='/path/to/your/ipa/redcity.ipa',
        Key=coskey, PartSize=10, MAXThread=10)
    print("market_url: " + response['Location'])
    sendWebhook(response['Location'], 'iOS包', timestamp)

3.5 发送企业微信通知

使用企业微信的 webhook,将打包成功的消息推送给相关人员。
关于企业微信机器人的学习使用,点击这里

def sendWebhook(url, package_type, timestamp):
    if(pushUrl != ''):
        content = f"{package_type} [n分支名:{target_branch}n时间:{timestamp}n下载链接(点击下载即可)]({url})"
        command = f"curl '{pushUrl}' -H 'Content-Type: application/json' -d '{{"msgtype": "markdown", "markdown": {{"content": "{content}"}}}}'"
        try:
            subprocess.run(command, shell=True, check=True)
            print("Webhook sent successfully.")
        except subprocess.CalledProcessError as e:
            print(f"Error sending webhook: {e}")

4. 运行脚本

  1. 将脚本文件保存为 auto_build.py
  2. 将路径和 COS 配置替换为自己的配置项。
  3. 在终端中执行脚本:
python auto_build.py

5. 总结

通过该脚本,我们实现了 Flutter 项目的自动打包、上传和通知的全流程自动化。它极大地减少了手动操作的步骤,并提升了开发效率。希望这篇文章对你有所帮助!

在实际使用中,你可以根据自己的需求对脚本进行进一步的定制和优化。Happy Coding!

阅读全文
下载说明:
1、本站所有资源均从互联网上收集整理而来,仅供学习交流之用,因此不包含技术服务请大家谅解!
2、本站不提供任何实质性的付费和支付资源,所有需要积分下载的资源均为网站运营赞助费用或者线下劳务费用!
3、本站所有资源仅用于学习及研究使用,您必须在下载后的24小时内删除所下载资源,切勿用于商业用途,否则由此引发的法律纠纷及连带责任本站和发布者概不承担!
4、本站站内提供的所有可下载资源,本站保证未做任何负面改动(不包含修复bug和完善功能等正面优化或二次开发),但本站不保证资源的准确性、安全性和完整性,用户下载后自行斟酌,我们以交流学习为目的,并不是所有的源码都100%无错或无bug!如有链接无法下载、失效或广告,请联系客服处理!
5、本站资源除标明原创外均来自网络整理,版权归原作者或本站特约原创作者所有,如侵犯到您的合法权益,请立即告知本站,本站将及时予与删除并致以最深的歉意!
6、如果您也有好的资源或教程,您可以投稿发布,成功分享后有站币奖励和额外收入!
7、如果您喜欢该资源,请支持官方正版资源,以得到更好的正版服务!
8、请您认真阅读上述内容,注册本站用户或下载本站资源即您同意上述内容!
原文链接:https://www.shuli.cc/?p=20290,转载请注明出处。
0

评论0

显示验证码
没有账号?注册  忘记密码?