Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get WORKSPACE directory in bazel rule

Tags:

bazel

I order to use clang tools like clang-format, clang-tidy or generate a compilation database like this, I need to know the WORKSPACE directory within the .bzl file. How can I obtain it? Consider the following example where I just want to print the full path of all the src files in my workspace:

# 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"])
)

Is there a cleaner/nicer way of doing this?

like image 564
Mike van Dyke Avatar asked Jan 31 '18 15:01

Mike van Dyke


2 Answers

You can probably get around this by using realpath. Something like:

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),
    }
)

Note the execution_requirements to get around the potential issues in my comment above.

like image 129
ahumesky Avatar answered Oct 13 '22 04:10

ahumesky


If you're like me and writing a repository_rule instead of a regular one, resolving the following label can help you: "@//:WORKSPACE"

Then use ctx.path to extract the required data: https://docs.bazel.build/versions/master/skylark/lib/repository_ctx.html#path

like image 42
Alexey Soshin Avatar answered Oct 13 '22 04:10

Alexey Soshin