Bazel相当于Buck的classpath

时间:2019-12-13 15:24:36

标签: java bazel

我正在尝试将项目从buck迁移到bazel,并寻找与genrules等效的 $(classpath)宏。在bazel中是否可以使用类似的东西来获取给定java_library的类路径的jar列表?

我能想到的最好的方法是遍历依赖项列表,并使用 $(execpath)宏获取对应的jar:

jar_deps = []
for dep in deps: # deps are the same dependencies specified for the java_library
    jar_deps.append("$(execpath %s)" % dep)

genrule(
    name = "test-rule",
    outs = ["test-rule.txt"],
    deps = deps,
    cmd  = "echo \"%s\" > $@" % (":".join(jar_deps)),
)

有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

看来,实现此目标的另一种方法是使用自定义规则访问Java规则的 JavaInfo 提供程序:

def _runtime_deps_providing_rule_impl(ctx):
  return [
    platform_common.TemplateVariableInfo({
      "RUNTIME_DEPS": ":".join([f.path for f in ctx.attr.rule[JavaInfo].transitive_runtime_deps.to_list()]),
    })
  ]

runtime_deps_providing_rule = rule(
  implementation = _runtime_deps_providing_rule_impl,
  attrs = {
    "rule": attr.label(),
  },
)

runtime_deps_providing_rule(
  name = "test-providing-rule",
  rule = ":test-java-rule",
)

genrule(
  name = "test-rule",
  outs = ["test-rule.txt"],
  cmd = "echo \"$(RUNTIME_DEPS)\" > $@",
  toolchains = [":test-providing-rule"],
)

这样做的好处是不需要显式传递依赖项列表。