1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
|
""" 多渠道打包系统 支持不同渠道的资源替换和配置 """
import os import json import shutil import zipfile from datetime import datetime
class ChannelConfig: """渠道配置类"""
def __init__(self, config_file='channels.json'): self.config_file = config_file self.channels = self.load_config()
def load_config(self): """加载渠道配置""" if os.path.exists(self.config_file): with open(self.config_file, 'r', encoding='utf-8') as f: return json.load(f) return self.get_default_config()
def get_default_config(self): """默认渠道配置""" return { "google": { "name": "Google Play", "package_name": "com.yourgame.google", "app_name": "Your Game", "icon": "channels/google/icon.png", "splash": "channels/google/splash.png", "sdk_config": { "analytics": "firebase", "ads": "admob" }, "extra_files": [ "channels/google/google-services.json" ] }, "huawei": { "name": "Huawei AppGallery", "package_name": "com.yourgame.huawei", "app_name": "Your Game", "icon": "channels/huawei/icon.png", "splash": "channels/huawei/splash.png", "sdk_config": { "analytics": "hms", "ads": "huawei_ads" }, "extra_files": [ "channels/huawei/agconnect-services.json" ] }, "xiaomi": { "name": "Xiaomi Store", "package_name": "com.yourgame.xiaomi", "app_name": "Your Game", "icon": "channels/xiaomi/icon.png", "splash": "channels/xiaomi/splash.png", "sdk_config": { "analytics": "xiaomi", "ads": "xiaomi_ads" }, "extra_files": [] } }
def save_config(self): """保存配置到文件""" with open(self.config_file, 'w', encoding='utf-8') as f: json.dump(self.channels, f, indent=2, ensure_ascii=False)
def get_channel(self, channel_id): """获取指定渠道配置""" return self.channels.get(channel_id)
class ChannelPackager: """渠道打包器"""
def __init__(self, build_dir='./build/web-mobile/'): self.build_dir = build_dir self.config = ChannelConfig() self.output_dir = './output/'
if not os.path.exists(self.output_dir): os.makedirs(self.output_dir)
def package_channel(self, channel_id, version='1.0.0'): """ 为指定渠道打包
Args: channel_id: 渠道标识 version: 版本号
Returns: str: 输出文件路径 """ channel = self.config.get_channel(channel_id) if not channel: raise ValueError(f"Unknown channel: {channel_id}")
print(f"\n{'='*60}") print(f"Packaging for channel: {channel['name']}") print(f"{'='*60}\n")
temp_dir = f"./temp_{channel_id}/" if os.path.exists(temp_dir): shutil.rmtree(temp_dir) shutil.copytree(self.build_dir, temp_dir)
self.replace_channel_resources(temp_dir, channel)
self.update_config_files(temp_dir, channel, version)
self.copy_extra_files(temp_dir, channel)
self.generate_version_info(temp_dir, channel, version)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') output_name = f"game_{channel_id}_v{version}_{timestamp}.zip" output_path = os.path.join(self.output_dir, output_name)
self.create_zip(temp_dir, output_path, channel_id)
shutil.rmtree(temp_dir)
print(f"\n✓ Package created: {output_path}") return output_path
def replace_channel_resources(self, target_dir, channel): """替换渠道特定资源""" print("Replacing channel resources...")
if 'icon' in channel and os.path.exists(channel['icon']): icon_target = os.path.join(target_dir, 'icon.png') shutil.copy2(channel['icon'], icon_target) print(f" ✓ Icon replaced: {channel['icon']}")
if 'splash' in channel and os.path.exists(channel['splash']): splash_target = os.path.join(target_dir, 'splash.png') shutil.copy2(channel['splash'], splash_target) print(f" ✓ Splash replaced: {channel['splash']}")
def update_config_files(self, target_dir, channel, version): """更新配置文件""" print("Updating configuration files...")
config_file = os.path.join(target_dir, 'config.json') if os.path.exists(config_file): with open(config_file, 'r', encoding='utf-8') as f: config = json.load(f)
config['packageName'] = channel['package_name'] config['version'] = version config['channel'] = channel['name'] config['sdk'] = channel.get('sdk_config', {})
with open(config_file, 'w', encoding='utf-8') as f: json.dump(config, f, indent=2, ensure_ascii=False)
print(f" ✓ Config updated: {config_file}")
def copy_extra_files(self, target_dir, channel): """复制额外文件""" if 'extra_files' not in channel: return
print("Copying extra files...") for file_path in channel['extra_files']: if os.path.exists(file_path): target_path = os.path.join(target_dir, os.path.basename(file_path)) shutil.copy2(file_path, target_path) print(f" ✓ Copied: {file_path}") else: print(f" ⚠ Not found: {file_path}")
def generate_version_info(self, target_dir, channel, version): """生成版本信息文件""" version_info = { 'channel': channel['name'], 'channel_id': channel.get('id', 'unknown'), 'version': version, 'build_time': datetime.now().isoformat(), 'package_name': channel['package_name'] }
version_file = os.path.join(target_dir, 'version.json') with open(version_file, 'w', encoding='utf-8') as f: json.dump(version_info, f, indent=2, ensure_ascii=False)
print(f" ✓ Version info generated")
def create_zip(self, source_dir, output_file, basedir): """创建 ZIP 文件""" print(f"\nCreating ZIP archive...")
with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as zf: for dirpath, dirnames, filenames in os.walk(source_dir): arcroot = dirpath.replace(source_dir, '').lstrip(os.sep)
for filename in filenames: filepath = os.path.join(dirpath, filename) arcname = os.path.join(basedir, arcroot, filename) zf.write(filepath, arcname)
size = os.path.getsize(output_file) print(f" ✓ Archive created: {size / 1024 / 1024:.2f} MB")
def package_all_channels(self, version='1.0.0'): """为所有渠道打包""" results = {}
for channel_id in self.config.channels: try: output_path = self.package_channel(channel_id, version) results[channel_id] = { 'success': True, 'path': output_path } except Exception as e: results[channel_id] = { 'success': False, 'error': str(e) }
print(f"\n{'='*60}") print("Packaging Summary") print(f"{'='*60}")
for channel_id, result in results.items(): status = "✓ SUCCESS" if result['success'] else "✗ FAILED" print(f"{channel_id:15} {status}") if result['success']: print(f" Output: {result['path']}") else: print(f" Error: {result['error']}")
return results
if __name__ == '__main__': packager = ChannelPackager()
packager.package_all_channels(version='1.2.3')
|