| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- import subprocess
- import os
- import datetime
- import shutil
- import re
- # 项目根目录
- PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
- # APK 目录
- APK_DIR = os.path.join(PROJECT_ROOT, "build", "app", "outputs", "flutter-apk")
- RENAMED_DIR = os.path.join(PROJECT_ROOT,"build", "app", "outputs", "renamed")
- def get_version_name():
- # 读取 Flutter 版本号(pubspec.yaml),无需 yaml 依赖
- with open("pubspec.yaml", "r", encoding="utf-8") as f:
- content = f.read()
- match = re.search(r'version:\s*([\d.]+)', content)
- if match:
- return match.group(1) # e.g. "1.6.0"
- return "1.0.0" # 默认值
- # 删除旧 APK 文件
- def clean_old_apks():
- if not os.path.exists(APK_DIR):
- return
- for filename in os.listdir(APK_DIR):
- if filename.endswith(".apk"):
- file_path = os.path.join(APK_DIR, filename)
- try:
- os.remove(file_path)
- print(f"🗑️ 已删除旧 APK:{file_path}")
- except Exception as e:
- print(f"⚠️ 删除失败:{file_path} -> {e}")
- def clean_renamed_apks():
- if not os.path.exists(RENAMED_DIR):
- return
- for file in os.listdir(RENAMED_DIR):
- if file.endswith(".apk"):
- file_path = os.path.join(RENAMED_DIR, file)
- try:
- os.remove(file_path)
- print(f"🗑️ 删除重命名目录中的旧 APK:{file_path}")
- except Exception as e:
- print(f"⚠️ 删除失败:{file_path} -> {e}")
- # 执行 flutter build 命令
- def build_apk():
- result = subprocess.run("flutter build apk --release", shell=True)
- if result.returncode != 0:
- raise Exception("Flutter build failed")
- # 重命名 APK
- def rename_apk(version_name):
- timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
- src = "build/app/outputs/flutter-apk/app-release.apk"
- if not os.path.exists(src):
- raise FileNotFoundError(f"未找到 {src}")
- # 输出目录
- dst_dir = "build/app/outputs/renamed/"
- os.makedirs(dst_dir, exist_ok=True)
- dst = os.path.join(dst_dir, f"app_{version_name}_{timestamp}.apk")
- shutil.copy(src, dst)
- print(f"✅ 已生成 APK:{dst}")
- if __name__ == "__main__":
- try:
- version = get_version_name()
- print(f"📦 版本号: {version}")
- clean_old_apks()
- clean_renamed_apks()
- print("🚀 开始构建 APK ...")
- build_apk()
- rename_apk(version)
- except Exception as e:
- print(f"❌ 出错啦: {e}")
|