bazelbuild / rules_rust

Rust rules for Bazel
https://bazelbuild.github.io/rules_rust/
Apache License 2.0
651 stars 412 forks source link

Feature request: some way to get the Bazel execroot in build.rs #1555

Closed bsilver8192 closed 1 week ago

bsilver8192 commented 1 year ago

I would like a way to access the Bazel execroot path from build.rs, so I can run commands from that directory.

Specifically, I'm using cc::Build with a custom Bazel toolchain. It mostly works, except my toolchain has relative paths, so the ${CC} needs to be run from the execroot. For my situation, I don't mind writing a wrapper that changes directories and calls the underlying compiler, but I need to know which directory to use. Putting the absolute path in an environment would be fine, but I'm not sure if there are any problems with exposing that path to build.rs scripts.

For now I'm just looking for my Bazel workspace's name in ${CARGO_MANIFEST_DIR}, which should be fairly robust but is kind of hacky.

This could form part of the solution to #931.

bsilver8192 commented 1 year ago

In addition to the execroot, the path between the root of the runfiles tree (xyz.runfiles/repository_name) and ${CARGO_MANIFEST_DIR} would be helpful, that's the most common thing I find myself trying to derive.

illicitonion commented 1 year ago

We currently do ${pwd}-substitution on the build_script_env attribute: https://github.com/bazelbuild/rules_rust/blob/7ffe0a5556a35f8c11bf9a9ae8bc4020dd44ea13/cargo/cargo_build_script_runner/bin.rs#L108-L114

So if you were to write:

cargo_build_script(
    ...
    build_script_env = {
        "EXEC_ROOT": "${pwd}",
    },
)

I think you'd end up being able to access the exec root? Not necessarily the ideal API, but I think it should work...

Then for runfiles-based lookups, you may be able to use the runfiles library for this: https://github.com/bazelbuild/rules_rust/blob/main/tools/runfiles/runfiles.rs assuming we don't terribly break things with how we run cargo_build_scripts - can you give it a go?

bsilver8192 commented 1 year ago

Yes, that does work. It needs a level of escaping for reference:

'TEST': '$${pwd}',
UebelAndre commented 1 week ago

Closing this as a solution seems to have been found!