Bazel responsitory_rule 創建一個 rule

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",
)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章