d6b1dcf8Add on Dec 31, 2025History
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WdLoader编译脚本 - 使用Cython编译WdLoader
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path


def check_dependencies():
    """检查依赖项"""
    print("检查依赖项...")
    
    try:
        import cython
        print(f"✓ Cython版本: {cython.__version__}")
    except ImportError:
        print("✗ Cython未安装")
        return False
    
    try:
        import cryptography
        print(f"✓ Cryptography版本: {cryptography.__version__}")
    except ImportError:
        print("✗ Cryptography未安装")
        return False
    
    return True


def install_dependencies():
    """安装依赖项"""
    print("安装依赖项...")
    
    try:
        subprocess.run([
            sys.executable, "-m", "pip", "install", "-r", "requirements.txt"
        ], check=True)
        print("✓ 依赖项安装成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 依赖项安装失败: {e}")
        return False


def compile_with_cython():
    """使用Cython编译"""
    print("使用Cython编译...")
    
    try:
        # 编译命令
        subprocess.run([
            sys.executable, "setup.py", "build_ext", "--inplace"
        ], check=True)
        print("✓ Cython编译成功")
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ Cython编译失败: {e}")
        return False


def create_compiled_test():
    """创建编译版本的测试脚本"""
    print("创建编译版本测试脚本...")
    
    test_content = """#!/usr/bin/env python3
# -*- coding: utf-8 -*-
\"\"\"
WdLoader编译版本测试脚本
\"\"\"

try:
    # 尝试导入编译版本
    import WdLoader_compiled as WdLoader
    print("✓ 使用编译版本")
except ImportError:
    # 回退到源码版本
    import WdLoader
    print("⚠ 使用源码版本")

from encrypt_tool import EncryptTool
import time


def test_compiled_version():
    \"\"\"测试编译版本\"\"\"
    print("=" * 50)
    print("测试编译版本性能")
    print("=" * 50)
    
    encrypt_tool = EncryptTool()
    loader = WdLoader.WdLoader()
    
    # 简单测试
    test_code = "def test(): return 'compiled test success'"
    
    print("测试编译版本功能...")
    encrypted = encrypt_tool.encrypt(test_code)
    result = loader.run(encrypted, "test")
    print(f"测试结果: {result}")
    
    if result == 'compiled test success':
        print("✓ 编译版本测试通过")
    else:
        print("✗ 编译版本测试失败")


if __name__ == "__main__":
    print("WdLoader编译版本测试开始")
    print("时间:", time.strftime("%Y-%m-%d %H:%M:%S"))
    
    try:
        test_compiled_version()
        print("\\n编译版本测试完成!")
    except Exception as e:
        print(f"测试过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
"""
    
    with open("test_compiled.py", "w", encoding="utf-8") as f:
        f.write(test_content)
    
    print("✓ 编译版本测试脚本创建成功")


def clean_build_files():
    """清理构建文件"""
    print("清理构建文件...")
    
    patterns = ["build", "*.c", "*.so", "*.pyd", "__pycache__"]
    
    for pattern in patterns:
        if pattern == "build":
            if os.path.exists(pattern):
                shutil.rmtree(pattern)
                print(f"✓ 删除目录: {pattern}")
        else:
            for file_path in Path(".").glob(pattern):
                if file_path.is_file():
                    file_path.unlink()
                    print(f"✓ 删除文件: {file_path}")
                elif file_path.is_dir():
                    shutil.rmtree(file_path)
                    print(f"✓ 删除目录: {file_path}")


def main():
    """主函数"""
    print("WdLoader编译脚本")
    print("=" * 50)
    
    # 检查依赖项
    if not check_dependencies():
        print("\n尝试安装依赖项...")
        if not install_dependencies():
            print("依赖项安装失败,请手动安装:")
            print("pip install -r requirements.txt")
            return False
    
    # 清理旧的构建文件
    clean_build_files()
    
    # 编译
    if compile_with_cython():
        print("\n编译成功!")
        
        # 创建测试脚本
        create_compiled_test()
        
        print("\n使用方法:")
        print("1. 运行编译版本测试: python test_compiled.py")
        print("2. 清理构建文件: python compile.py --clean")
        
        return True
    else:
        print("\n编译失败!")
        return False


if __name__ == "__main__":
    if len(sys.argv) > 1 and sys.argv[1] == "--clean":
        clean_build_files()
        print("构建文件清理完成")
    else:
        success = main()
        sys.exit(0 if success else 1)