我想导入在json文件(my_info.json)中定义的变量作为bazel规则的属性。我试过这个方法(https://docs.bazel.build/versions/5.3.1/skylark/tutorial-sharing-variables.html),但不想使用.bzl文件,直接导入变量到BUILD. bazel的属性。
我想使用那些从my_info.json导入的变量作为其他BULD.bazel文件的属性。
projects/python_web/BUILD.bazel
load("//projects/tools/parser:config.bzl", "MY_REPO","MY_IMAGE")
container_push(
name = "publish",
format = "Docker",
registry = "registry.hub.docker.com",
repository = MY_REPO,
image = MY_IMAGE,
tag = "1",
)
在Bazel slack中询问类似的问题时,我被告知,无法直接将变量导入Bazel,需要解析json变量并将其写入.bzl文件。
我也试过这段代码,但没有写在config.bzl文件中。
my_info.json
{
"MYREPO" : "registry.hub.docker.com",
"MYIMAGE" : "michael/monorepo-python-web"
}
WORKSPACE.bazel
load("//projects/tools/parser:jsonparser.bzl", "load_my_json")
load_my_json(
name = "myjson"
)
projects/tools/parser/jsonparser.bzl
def _load_my_json_impl(repository_ctx):
json_data = json.decode(repository_ctx.read(repository_ctx.path(Label(":my_info.json"))))
config_lines = ["%s = %s" % (key, repr(val)) for key, val in json_data.items()]
repository_ctx.file("config.bzl", "\n".join(config_lines))
load_my_json = repository_rule(
implementation = _load_my_json_impl,
attrs = {},
)
projects/tools/parser/BUILD.bazel
load("@aspect_bazel_lib//lib:yq.bzl", "yq")
load(":config.bzl", "MYREPO", "MY_IMAGE")
yq(
name = "convert",
srcs = ["my_info2.json"],
args = ["-P"],
outs = ["bar.yaml"],
)
正在执行:% bazel build projects/tools/parser:convert
ERROR: Traceback (most recent call last):
File "/Users/michael.taquia/Documents/Personal/Projects/bazel/bazel-projects/multi-language-bazel-monorepo/projects/tools/parser/BUILD.bazel", line 2, column 22, in <toplevel>
load(":config.bzl", "MYREPO", "MY_IMAGE")
Error: file ':config.bzl' does not contain symbol 'MYREPO'
在进行故障排除时,我看到执行调用了jsonparser.bzl,但从未进入**_load_my_json_impl函数(基于print语句),也没有向config.bzl**写入任何内容。
注意:已在macOS 12.6(21 G115)达尔文Kernel版本21.6.0上测试
There is a better way to do that? A code snippet will be very useful.
1条答案
按热度按时间pokxtpni1#
Bazel总是在三个阶段工作:
1.分析-解释规则(impl)以产生动作
1.执行-动作(例如“运行gcc with args”)执行
不幸的是,在解决方案中,你已经描述了你的“负载”取决于“分析”的结果。
我希望Bazel能够在加载阶段加载json/yaml/whatever-bazel-agnostic…即使在“负载”中提升“.bzl”扩展要求也是一种解脱。