Files
wnmj/proj.android/build_ndk.py

156 lines
4.5 KiB
Python
Raw Permalink Normal View History

2026-03-01 14:03:17 +08:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
NDK 编译脚本
在编译前将 GBK 编码的源文件临时转换为 UTF-8编译后恢复
"""
import os
import sys
import shutil
import subprocess
import glob
# 项目根目录
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CLASSES_DIR = os.path.join(PROJECT_ROOT, "Classes")
BACKUP_DIR = os.path.join(PROJECT_ROOT, "proj.android", ".gbk_backup")
# NDK 路径
NDK_BUILD = r"D:\Android\sdk\ndk\16.1.4479499\ndk-build.cmd"
def find_gbk_files():
"""查找可能包含 GBK 编码中文的源文件"""
gbk_files = []
extensions = ['*.cpp', '*.h', '*.c']
for ext in extensions:
pattern = os.path.join(CLASSES_DIR, '**', ext)
for filepath in glob.glob(pattern, recursive=True):
try:
with open(filepath, 'rb') as f:
content = f.read()
# 检查是否包含非 ASCII 字节(可能是中文)
has_non_ascii = any(b > 127 for b in content)
if has_non_ascii:
# 尝试用 UTF-8 解码,如果失败则可能是 GBK
try:
content.decode('utf-8')
except UnicodeDecodeError:
gbk_files.append(filepath)
except Exception as e:
print(f"Error checking {filepath}: {e}")
return gbk_files
def convert_to_utf8(filepath):
"""将 GBK 文件转换为 UTF-8"""
try:
with open(filepath, 'rb') as f:
content = f.read()
# 解码 GBK
text = content.decode('gbk', errors='replace')
# 编码为 UTF-8
with open(filepath, 'wb') as f:
f.write(text.encode('utf-8'))
return True
except Exception as e:
print(f"Error converting {filepath}: {e}")
return False
def backup_files(files):
"""备份原始 GBK 文件"""
if os.path.exists(BACKUP_DIR):
shutil.rmtree(BACKUP_DIR)
os.makedirs(BACKUP_DIR)
for filepath in files:
rel_path = os.path.relpath(filepath, PROJECT_ROOT)
backup_path = os.path.join(BACKUP_DIR, rel_path)
os.makedirs(os.path.dirname(backup_path), exist_ok=True)
shutil.copy2(filepath, backup_path)
print(f"Backed up {len(files)} files")
def restore_files(files):
"""从备份恢复原始 GBK 文件"""
restored = 0
for filepath in files:
rel_path = os.path.relpath(filepath, PROJECT_ROOT)
backup_path = os.path.join(BACKUP_DIR, rel_path)
if os.path.exists(backup_path):
shutil.copy2(backup_path, filepath)
restored += 1
print(f"Restored {restored} files")
# 清理备份目录
if os.path.exists(BACKUP_DIR):
shutil.rmtree(BACKUP_DIR)
def run_ndk_build(debug=False):
"""运行 ndk-build"""
os.chdir(os.path.join(PROJECT_ROOT, "proj.android"))
cmd = NDK_BUILD
if not debug:
cmd += " NDK_DEBUG=0"
print(f"Running: {cmd}")
# 使用 os.system 来直接执行命令并显示输出
return_code = os.system(cmd)
return return_code == 0
def main():
print("=" * 60)
print("NDK Build Script with GBK->UTF-8 Conversion")
print("=" * 60)
# 1. 查找 GBK 文件
print("\n[1/5] Finding GBK encoded files...")
gbk_files = find_gbk_files()
print(f"Found {len(gbk_files)} GBK files")
if not gbk_files:
print("No GBK files found, running ndk-build directly...")
success = run_ndk_build()
sys.exit(0 if success else 1)
# 2. 备份原始文件
print("\n[2/5] Backing up original files...")
backup_files(gbk_files)
# 3. 转换为 UTF-8
print("\n[3/5] Converting to UTF-8...")
converted = 0
for filepath in gbk_files:
if convert_to_utf8(filepath):
converted += 1
print(f" Converted: {os.path.relpath(filepath, PROJECT_ROOT)}")
print(f"Converted {converted} files")
# 4. 运行 ndk-build
print("\n[4/5] Running ndk-build...")
success = run_ndk_build()
# 5. 恢复原始文件
print("\n[5/5] Restoring original GBK files...")
restore_files(gbk_files)
if success:
print("\n" + "=" * 60)
print("BUILD SUCCESSFUL!")
print("=" * 60)
else:
print("\n" + "=" * 60)
print("BUILD FAILED!")
print("=" * 60)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()