• OpenHarmony移植案例: build lite源码分析之hb命令__entry__.py


    摘要:本文介绍了build lite 轻量级编译构建系统hb命令的源码,主要分析了_\entry__.py文件。

    本文分享自华为云社区《移植案例与原理 - build lite源码分析 之 hb命令__entry__.py》,作者:zhushy 。

    hb命令可以通过python pip包管理器进行安装,应该是OpenHarmony Build的缩写,在python包名称是ohos-build。hb作为编译构建子系统提供的命令行,用于编译构建产品、芯片厂商组件或者单个组件。我们来学习hb命令行工具的源码,本文主要分析下文件openharmony/build/lite/hb/__entry__.py。

    1、find_top()函数

    find_top()函数用于获取OpenHarmony源代码根目录,之前的系列文章分析过。代码也较简单,不再赘述。

    def find_top():
     cur_dir = os.getcwd()
     while cur_dir != "/":
     hb_internal = os.path.join(cur_dir, 'build/lite/hb_internal')
     if os.path.exists(hb_internal):
     return cur_dir
     cur_dir = os.path.dirname(cur_dir)
     raise Exception("Please call hb utilities inside source root directory")

    2、get_hb_commands()函数

    get_hb_commands()函数用于返回hb命令行工具支持的命令集。hb支持的命令定义在文件’build/lite/hb_internal/hb_command_set.json’中,支持的命令主要为build、set、env、clean和tool。

    def get_hb_commands(config_file):
     if not os.path.exists(config_file):
     raise Exception('Error: {} not exist, couldnot get hb command set'.format(config_file))
     with open(config_file, 'r') as file:
            config = json.load(file)
     return config

    3、main()函数

    在main()函数中,首先获取OpenHarmony源代码根目录,然后把路径'build/lite'插入到sys.path系统搜索路径,为后续调用importlib.import_module接口进行动态加载做准备。⑴处定义hb命令行的支持的选项,使用和命令输出hb -h结合起来学习源代码。⑵处获取hb命令行工具支持的命令集合,然后添加到命令行解析参数列表里parser_list。⑶和⑷配置支持的positional arguments(见 hb -h的输出),⑶处动态引入支持的模块,这些对应文件build/lite/hb_internal/hb_internal/XXX/XXX.py,其中XXX的取值为build、set、clean、env和tool。在这几个python文件中,都会有add_options()函数,用于提供具体命令的参数选项,还有个函数exec_command(),执行具体的命令时,会调用这些函数。⑷处的代码会配置刚才描述的add_options()函数和函数exec_command()。

    ⑸处的语句获取hb命令传入的参数选项,接下来动态加载’hb_internal.common.utils’,获得函数地址,分别用于控制台输出日志、异常处理等。接下来处理hb命令行传入的选项,⑹处如果指定了’-root’|’–root_path’选项时,开发者主动提供OpenHarmony源代码根目录,会执行args[0].root_path = topdir把根目录传入到参数列表里。⑺根据是hb tool还是其他命令,分别调用对应的函数exec_command(),命令行选项不一样时,传入的参数稍有差异,分别是args和args[0]。对于hb tool,args[1]会传递些要传递给gn命令行的参数gn_args。

    def main():
     try:
     topdir = find_top()
     except Exception as ex:
     return print("hb_error: Please call hb utilities inside source root directory")
     sys.path.insert(0, os.path.join(topdir, 'build/lite'))
    ⑴  parser = argparse.ArgumentParser(description='OHOS Build System '
     f'version {VERSION}')
     parser.add_argument('-v',
     '--version',
                            action='version',
                            version=f'[OHOS INFO] hb version {VERSION}')
     subparsers = parser.add_subparsers()
     parser_list = []
    ⑵ command_set = get_hb_commands(os.path.join(topdir, 'build/lite/hb_internal/hb_command_set.json'))
     for key, val in command_set.items():
     parser_list.append({'name': key, 'help': val})
     for each in parser_list:
     module_parser = subparsers.add_parser(name=each.get('name'),
     help=each.get('help'))
    ⑶      module = importlib.import_module('hb_internal.{0}.{0}'.format(
     each.get('name')))
    ⑷ module.add_options(module_parser)
     module_parser.set_defaults(parser=module_parser,
                                      command=module.exec_command)
    ⑸ args = parser.parse_known_args()
        module = importlib.import_module('hb_internal.common.utils')
     hb_error = getattr(module, 'hb_error')
     hb_warning = getattr(module, 'hb_warning')
     ohos_exception = getattr(module, 'OHOSException')
     try:
    ⑹ if args[0].parser.prog == 'hb set' and 'root_path' in vars(args[0]):
     # Root_path is topdir.
     args[0].root_path = topdir
    ⑺ if "tool" in args[0].parser.prog:
                status = args[0].command(args)
     else:
                status = args[0].command(args[0])
     except KeyboardInterrupt:
     hb_warning('User Abort')
            status = -1
     except ohos_exception as exception:
     hb_error(exception.args[0])
            status = -1
     except Exception as exception:
     if not hasattr(args[0], 'command'):
     parser.print_help()
     else:
     hb_error(traceback.format_exc())
     hb_error(f'Unhandled error: {exception}')
            status = -1
     return status

    4、参考站点

     

    5、小结

    本文介绍了build lite 轻量级编译构建系统hb命令的源码,主要分析了_\entry__.py文件。因为时间关系,仓促写作,或能力限制,若有失误之处,请各位读者多多指正。遗漏之处,欢迎补充。感谢阅读,有什么问题,请留言。

     

    点击关注,第一时间了解华为云新鲜技术~

  • 相关阅读:
    【python入门到放弃】冒泡排序
    【python入门到放弃】变量、常量与注释
    环信和融云实现跨应用聊天
    swift里类方法和构造方法的使用来减少代码冗余提高开发效率
    git 常用命令 使用及iOS开发使用git管理项目步骤
    获取IPA包文件中的图片资源
    iOS11适配和iPhonex适配资料收集整理
    IOS 开发delegate和block的区别整理资料收集 (文章中内容有参考网络资料)
    IOS开发中集合操作 处理数据的 交集 并集 差集
    联系苹果人员的方式(转)
  • 原文地址:https://www.cnblogs.com/huaweiyun/p/16868838.html
Copyright © 2020-2023  润新知