Bazel responsitory

    技术2022-07-11  121

    bazel

    respository_rule

    主要功能是创建一个workspace 空间。对于package 内部的BUILD.tpl文件target 可以使用 responsity_ctx.file("//package") 创建 BUILD文件,或者repository_ctx.template(“BUILD”, build_tpl, {})对BUILD文件进行修改,然后通过@< name>//package:target 进行引用。 这个rule 当你创建的时候就会加载,这时Bazel 就会运行rule里面的 implementation 函数,这个implementation 函数描述了如何创建responsity、内容和BUILD文件。

    一个简单的例子:

    # 环境变量 _ENVIRONS = [ _GCC_HOST_COMPILER_PATH, "GCC_HOST_COMPILER_PATH", "GCC_HOST_COMPILER_PREFIX", "TF_NEED_CUDA", "TF_CUDA_CLANG", "TF_CUDA_PATHS", "NVVMIR_LIBRARY_DIR", ] def raw_exec(responsitory_ctx, cmdline): # 使用 responsitory_ctx.execute() 执行cmdline return responsotory_ctx.execute(cmdline) def get_cpu_value(responsitory_ctx): # 获取系统类型 if is_windows(responsitory_ctx): return "Windows" # 如果是mac os ,result 是 Darwin # linux 系统, result 是 Linux result = raw_exe(responsitory_ctx, ["uname", "-s"]) return result.stdout.strip() # 加载template 文件 def _tpl(responsitory_ctx, tpl, substitutions = {}, out=None): if not out: out = tpl.replace(":", "/") respinsitory_ctx.template( out, Label("//example/%s.tpl" % tpl), substitutions, ) def _create_local_responsity(responsitory_ctx): cpu_value = get_cpu_value() # 加载template 文件,替换文件中的 %{cuda_is_configure}为 指定的值 _tpl(respinsitory_ctx, "cuda:build_defs.bzl", { "%{cuda_is_configure}": "False" } ) # 创建文件 "cuda/cuda/include/cuda.h" repository_ctx.file("cuda/cuda/include/cuda.h") example_configure = respository_rule( implementation = _create_local_responsity, environ =_ENVIRONS, remotable = True, attrs = { "environ": attr.string_dict(), } )

    定义了example_configue,首先就可以在bzl函数中执行

    example_configure(name="example_local")

    然后在bazel 或者BUILD文件中,可以引用

    load( "@example//:build_defs.bzl", "some_library", )
    Processed: 0.009, SQL: 9