1 Star 0 Fork 4

Enbo.H/oh-compile-script

forked from fengozl/oh-compile-script 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
conanbuild.py 13.31 KB
一键复制 编辑 原始数据 按行查看 历史
Wayne 提交于 2023-12-25 16:01 +08:00 . 适配conan2.0.14版本
import importlib
import os
import shutil
import sys
from multiprocessing import Process
from pathlib import Path
import yaml
import argparse
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger("conanbuild")
from collections import namedtuple
# 定义一个结构体
CliParam = namedtuple('CliParam',
['lib_name', 'lib_versions', 'build_type',
'options_shared', 'custom_install_path', 'custom_source_path', 'test_folder'])
def recuresive_copy_file(src_folder, target_folder):
if not os.path.exists(src_folder):
return
files = os.listdir(src_folder)
# 遍历文件列表
for file in files:
if os.path.isdir(src_folder + '/' + file):
if not os.path.exists(target_folder + '/' + file):
os.mkdir(target_folder + '/' + file)
recuresive_copy_file(src_folder + '/' + file, target_folder + '/' + file)
else:
if os.path.exists(target_folder + '/' + file):
os.remove(target_folder + '/' + file)
shutil.copyfile(src_folder + '/' + file, target_folder + '/' + file)
# OHOS sdk 路径
sdk_path = os.environ.get('OHOS_SDK')
def init_build_options_shared(lib_name):
options_shared = ""
deault_skip = [""]
default_true = [""]
default_false = [""]
with open(os.getcwd() + "/config/conan_build_args_mapping.yml", "r+") as args_mapping:
options = yaml.load(args_mapping, Loader=yaml.Loader).get("options")
shared_mapping = options.get("shared")
deault_skip = shared_mapping.get("skip")
default_true = shared_mapping.get("true_")
default_false = shared_mapping.get("false_")
args_mapping.close()
if deault_skip is not None and lib_name in deault_skip:
options_shared = "skip"
if default_true is not None and lib_name in map(str, default_true):
options_shared = "True"
if default_false is not None and lib_name in map(str, default_false):
options_shared = "False"
return options_shared
def init_test_folder_path(lib_name, lib_version):
tf_path = "test_package"
tf_skip_lists = []
with open(os.getcwd() + "/config/conan_build_args_mapping.yml", "r+") as args_mapping:
tf_lists = yaml.load(args_mapping, Loader=yaml.Loader).get("test_folder")
tf_skip_lists = tf_lists.get("skip")
args_mapping.close()
if tf_skip_lists is not None:
if [lib_name, lib_version] in tf_skip_lists:
tf_path = ""
if [lib_name, "all"] in tf_skip_lists:
tf_path = ""
return tf_path
def build_pre(options):
# 检查环境变量OHOS_SDK
if sdk_path is None:
print("Please set \"OHOS_SDK\" in your environment firstly!")
sys.exit()
# first get the library to be build
lib_name = options.lib_name
if lib_name is None or len(lib_name) == 0:
lib_name = input("Please input the supported library name (name is the folder name below "
"conan-center-index_ohos/recipes) : ")
lib_path = os.getcwd() + "/conan-center-index_ohos/recipes/" + lib_name
while not os.path.exists(lib_path) or not len(lib_name):
print("Unsupported lib name: [{}], please input again!".format(lib_name))
lib_name = input("Please input the supported library name (name is the folder name below "
"conan-center-index_ohos/recipes) : ")
lib_path = os.getcwd() + "/conan-center-index_ohos/recipes/" + lib_name
# get all valid versions from config.yml
lib_versions = []
with open('%s/config.yml' % lib_path, "r") as file:
lib_versions = yaml.load(file, Loader=yaml.Loader).get('versions')
lib_versions['all'] = {}
# get the build version
lib_version_ = options.lib_version
if lib_version_ is None or len(lib_version_) == 0:
print(list(lib_versions.keys()))
lib_version_ = input("Please input the version from the above list : ")
while not lib_version_ in lib_versions.keys():
# print(versions[version])
print(list(lib_versions.keys()))
lib_version_ = input("Please input the version from the above list : ")
build_type = options.build_type
if build_type is None or len(build_type) == 0:
build_type = input("Please set the build type (Debug or Release,empty for Release) : ")
if build_type == "Debug" or build_type == "debug":
build_type = "Debug"
else:
build_type = "Release"
options_shared = init_build_options_shared(lib_name)
if len(options_shared) == 0:
options_shared = options.options_shared
if options_shared is None or len(options_shared) == 0:
options_shared = input("Please set the compile target as static(False, default) or shared(True) : ")
while len(options_shared) > 0 and options_shared.upper() != 'FALSE' and options_shared.upper() != 'TRUE':
options_shared = input("Please input True、False or None:")
if options_shared.upper() == 'TRUE':
options_shared = 'True'
else:
options_shared = 'False'
test_folder = init_test_folder_path(lib_name, lib_version_)
custom_install_path = options.install_path
# 支持源码路径自定义,用于修改源码编译场景
custom_source_path = options.source_path
if lib_version_ != 'all':
lib_version_temp = {}
lib_version_temp[lib_version_] = lib_versions[lib_version_]
lib_versions = lib_version_temp
if custom_install_path is None or len(custom_install_path) == 0:
custom_install_path = input(
"Please input the install path(empty for {}/build/{}/{}/{}) : ".format(os.getcwd(), lib_name,
lib_version_, build_type))
if custom_source_path is None:
custom_source_path = input("Please set the custom source path(not necessary):")
if custom_source_path is not None and len(custom_source_path) > 0:
if not os.path.exists(custom_source_path):
logger.info("custom_source_path: {} is not exist!".format(custom_source_path))
sys.exit()
return CliParam(lib_name, lib_versions, build_type, options_shared, custom_install_path, custom_source_path,
test_folder)
# 一次编译所有版本
def build_versions(cli_param):
os.environ['ohos_build_root_lib_name'] = cli_param.lib_name # 用于标记顶层三方库的构建
os.environ['ohos_build_root_dir'] = os.getcwd() # 标记当前构建的根节点
options_shared = cli_param.options_shared
for lib_version in cli_param.lib_versions.keys():
if lib_version == 'all':
continue
logger.info("=======================start compile version:{}=======================".format(lib_version))
# concatenate the conan file path
conan_file_path = "{}/{}/recipes/{}/{}".format(os.getcwd(), "conan-center-index_ohos",
cli_param.lib_name,
cli_param.lib_versions[lib_version]['folder'])
# 处理profile信息,把profile文件生成到${pwd}/build/lib-name/lib-version目录下
if not os.path.exists(os.getcwd() + "/build"):
os.mkdir(os.getcwd() + "/build")
if not os.path.exists(os.getcwd() + "/build/" + cli_param.lib_name):
os.mkdir(os.getcwd() + "/build/" + cli_param.lib_name)
if not os.path.exists(os.getcwd() + "/build/" + cli_param.lib_name + '/' + lib_version):
os.mkdir(os.getcwd() + "/build/" + cli_param.lib_name + '/' + lib_version)
build_path = "{}/build/{}/{}".format(os.getcwd(), cli_param.lib_name, lib_version)
recuresive_copy_file(conan_file_path, build_path)
conan_file = "{}/conanfile.py".format(build_path)
profile_name = "profile_ohos"
original_content = ""
with open(os.getcwd() + "/config/%s" % profile_name, "r+") as file_object:
original_content = file_object.read()
file_object.close()
original_content = original_content.replace("%SDK_PATH%", sdk_path.replace("\\", "/"))
with open(build_path + "/ohos.temp.profile", "w+") as file_object:
file_object.write(original_content)
file_object.close()
install_path = cli_param.custom_install_path
customFlag = "custom"
if not install_path or not len(install_path):
install_path = build_path
customFlag = "default"
logger.info(
"=========={} install path:{}===========".format(customFlag, install_path + '/' + cli_param.build_type))
os.environ['ohos_build_root_install_path'] = str(Path(install_path + '/' + cli_param.build_type))
if cli_param.custom_source_path is not None and len(cli_param.custom_source_path) > 0:
os.environ['ohos_build_root_source_path'] = cli_param.custom_source_path
profile_path = build_path + "/ohos.temp.profile"
try:
import conan.cli.cli
args = [
"create",
conan_file,
"-s",
"build_type=%s" % cli_param.build_type,
"--profile=%s" % profile_path,
"--version=%s" % lib_version,
"--build=missing"
]
if len(options_shared) > 0 and options_shared != 'skip':
args.append("--options=shared=%s" % options_shared)
args.append("-tf=%s" % init_test_folder_path(cli_param.lib_name, lib_version))
conan.cli.cli.main(args)
except:
pass
logger.info("=======================end compile version:{}=======================".format(lib_version))
def modifySetting():
# setting.yml增加鸿蒙的支持
from conans.paths import get_conan_user_home
conan_home = get_conan_user_home()
setting_path = os.path.join(conan_home, "settings.yml")
if os.path.exists(setting_path):
if not os.path.exists(os.path.join(conan_home, "settings.yml.bak")):
shutil.copy(setting_path, setting_path + ".bak")
if os.stat(setting_path).st_size != os.stat(os.getcwd() + "/config/settings.yml").st_size:
shutil.copy(os.getcwd() + "/config/settings.yml", setting_path)
return
else:
shutil.copy(setting_path, setting_path + ".bak")
shutil.copy(os.getcwd() + "/config/settings.yml", setting_path)
def remove_cache_db():
cache_db_path = str(os.path.expanduser("~")) + "/.conan2/.conan.db"
if os.path.exists(cache_db_path):
os.remove(cache_db_path)
def modifyConanSource():
cli_module = importlib.import_module("conan.cli.cli")
path = Path(cli_module.__file__)
parent_dir = str(path.parents[2])
conan_version = cli_module.client_version
if conan_version not in ['2.0.12', '2.0.14']:
logger.info("Conan version {} is not support! Please install conan version 2.0.12 or 2.0.14.".format(conan_version))
sys.exit()
copy_flag = False
# 检查版本文件
if os.path.exists(os.getcwd() + "/adapter/.version"):
# 如果有,检查当前版本和版本文件中的版本号是否对应
with open(os.getcwd() + "/adapter/.version", "r+") as version_file:
version_str = str(version_file.read())
if version_str == conan_version:
# 是 跳过
version_file.close()
return
else:
# 否 则更换文件并重新将新的版本号写入
version_file.truncate(0)
version_file.seek(0, 0)
version_file.write(conan_version)
version_file.close()
# 删除缓存文件
remove_cache_db()
copy_flag = True
else:
# 如果没有就创建,并将当前conan版本号写入文件中
with open(os.getcwd() + "/adapter/.version", "w") as version_file:
version_file.write(conan_version)
version_file.close()
# 删除缓存文件
remove_cache_db()
copy_flag = True
if copy_flag:
recuresive_copy_file(os.getcwd() + '/adapter/'+conan_version, parent_dir)
if __name__ == '__main__':
p = Process(target=modifySetting, args=())
p.start()
p.join()
p1 = Process(target=modifyConanSource, args=())
p1.start()
p1.join()
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--lib', dest='lib_name', type=str,
help='当前支持的三方库,为conan-center-index_ohos/recipes的子目录名')
parser.add_argument('-v', '--version', dest='lib_version', type=str, help='version')
parser.add_argument('-t', '--build_type', dest='build_type', type=str, help='Debug or Release')
parser.add_argument('-i', '--install_path', dest='install_path', type=str, help='三方库的完成构建后的路径')
parser.add_argument('-s', '--source_path', dest='source_path', type=str, help='源码路径')
parser.add_argument('-p', '--options_shared', dest='options_shared', type=str,
help='编译三方库类型:False静态库(默认),True动态库')
options = parser.parse_args()
cli_param = build_pre(options)
build_versions(cli_param)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/enbo_h/oh-compile-script.git
git@gitee.com:enbo_h/oh-compile-script.git
enbo_h
oh-compile-script
oh-compile-script
master

搜索帮助