1

移植案例与原理 - Build Lite源码分析 之 Hb命令__Entry__.Py

 1 year ago
source link: https://www.51cto.com/article/721769.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

移植案例与原理 - Build Lite源码分析 之 Hb命令__Entry__.Py

作者:zhushangyuan_ 2022-11-01 15:29:03
本文介绍了Build Lite 轻量级编译构建系统HB命令的源码,主要分析了_\Entry__.Py文件。
b3768f93325d82b341d5491ccfde45d9fe0e70.png

​想了解更多关于开源的内容,请访问:​

​51CTO 开源基础软件社区​

​https://ost.51cto.com​

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、参考站点

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

​想了解更多关于开源的内容,请访问:​

​51CTO 开源基础软件社区​

​https://ost.51cto.com​。

责任编辑:jianghua 来源: 51CTO开源基础软件社区

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK