Zeitgeist
Zeitgeist

Reputation: 1520

Is it possible to get $pwd value from Bazel .bzl rule?

I am trying to get a value of the full current directory path from within .bzl rule. I have tried following:

  1. ctx.host_configuration.default_shell_env.PATH returns "/Users/[user_name]/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:...

  2. ctx.bin_dir.path returns bazel-out/local-fastbuild/bin

  3. pwd = ctx.expand_make_variables("cmd", "$$PWD", {}) returns string $PWD - I don't think this rule is helpful for me, but may be just using it wrong.

What I need is the directory under which the cmd that runs Bazel .bzl rule is running. For example: /Users/[user_name]/git/workspace/path/to/bazel/rule.bzl or at least first part of the path prior to the WORKSPACE directory.

I can't use pwd because I need this value before I call ctx.actions.run_shell()

Are there no attributes in Bazel configurations that hold this value?

Upvotes: 5

Views: 6418

Answers (1)

Laurent
Laurent

Reputation: 2999

The goal is to have hermetic builds, so you shouldn't depend on the absolute path.

Feel free to use pwd inside the command of ctx.actions.run_shell() (for reproducible builds, be careful, avoid putting the absolute path in the generated files).


Edit. Technically, there are some workarounds. For example, you can pass the path via the --define flag:

bazel build :all --define=path=$(pwd)

Then the value will be available using ctx.var["path"].


Based on your comment below, you want the path to declare an output. Let me repeat: You shouldn't use an absolute path to declare the output file. Declare an output in your package. Then ask the tool you call to use that output.

For example, when you call gcc, you can use -o to specify the output. When a tool writes to stdout, use the shell to redirect it. If the tool is really not flexible, you may want to wrap it with your own script (e.g. call the tool and copy the output file).

Using an absolute path here is not the right solution. For example, it should be possible to execute the action on a remote machine (where your absolute path won't make sense.

Zip may be a reasonable solution. It's useful when you cannot know in advance the number or the names of the output files.

Upvotes: 4

Related Questions