如何在bazel规则中获取WORKSPACE目录

时间:2018-01-31 15:20:53

标签: bazel

我命令使用clang-formatclang-tidy之类的clang工具或生成compilation database之类的this,我需要知道.bzl文件中的WORKSPACE目录。我怎样才能获得它?考虑以下示例,我只想在工作区中打印所有src文件的完整路径:

# simple_example.bzl

def _impl(ctx):
  workspace_dir = // ---> what comes here? <---
  command = "\n".join([echo %s/%s" % (workspace_dir, f.short_path) 
                       for f in ctx.files.srcs])

  ctx.actions.write(
      output=ctx.outputs.executable,
      content=command,
      is_executable=True)


echo_full_path = rule(
    implementation=_impl,
    executable=True,
    attrs={
      "srcs": attr.label_list(allow_files=True),
    }
)

# BUILD

echo_full_path(
    name = "echo",
    srcs = glob(["src/**/*.cc"])
)

有更清洁/更好的方法吗?

3 个答案:

答案 0 :(得分:1)

您可以使用realpath解决此问题。类似的东西:

def _impl(ctx):

  ctx.actions.run_shell(
    inputs = ctx.files.srcs,
    outputs = [ctx.outputs.executable],
    command = "\n".join(["echo echo $(realpath \"%s\") >> %s" (f.path,
              ctx.outputs.executable.path) for f in ctx.files.srcs]),
    execution_requirements = {
        "no-sandbox": "1",
        "no-cache": "1",
        "no-remote": "1",
        "local": "1",
    },
  )

echo_full_path = rule(
    implementation=_impl,
    executable=True,
    attrs={
      "srcs": attr.label_list(allow_files=True),
    }
)

请注意execution_requirements以解决上述评论中的潜在问题。

答案 1 :(得分:1)

如果您像我一样,写了repository_rule而不是普通的标签,则解决以下标签可以为您提供帮助:"@//:WORKSPACE"

然后使用ctx.path提取所需的数据:https://docs.bazel.build/versions/master/skylark/lib/repository_ctx.html#path

答案 2 :(得分:1)

我修改了@ahumesky的规则,以隐式使用BUILD文件作为源,并只写入工作区目录一次:

workspace.bzl

def _write_workspace_dir_impl(ctx):
    src = ctx.files._src[0]
    out = ctx.actions.declare_file(ctx.label.name)
    ctx.actions.run_shell(
        inputs = ctx.files._src,
        outputs = [out],
        command = """
          full_path="$(readlink -f -- "{src_full}")"
          # Trim the src.short_path suffix from full_path. Double braces to
          # output literal brace for shell.
          echo "${{full_path%/{src_short}}}" >> {out_full}
        """.format(src_full = src.path, src_short = src.short_path, out_full = out.path),
        execution_requirements = {
            "no-sandbox": "1",
            "no-remote": "1",
            "local": "1",
        },
    )
    return [DefaultInfo(files = depset([out]))]

write_workspace_dir = rule(
    implementation = _write_workspace_dir_impl,
    attrs = {
        "_src": attr.label(allow_files = True, default = "BUILD"),
    },
    doc = "Writes the full path of the current workspace dir to a file.",
)

已构建

load(":workspace.bzl", "write_workspace_dir")

write_workspace_dir(
    name = "workspace_dir",
)

示例输出

bazel build //build/bazel:workspace_dir
INFO: Analyzed target //build/bazel:workspace_dir 
INFO: Build completed successfully, 1 total action

cat bazel-bin/build/bazel/workspace_dir
/p/$MY_PROJECT