How to make a path from a string in starlark?

3.3k Views Asked by At

I'm writing some validation code for a bazel build rule and I need to do some path validation. I need to check that a certain file exists in the same directory as the BUILD file. I notice that there's a context attribute build_file_path which points to the BUILD file. I'd like to extract the parent directory from this.

It looks like I can't create a new path object - I don't see a constructor/initializer. It also seems like Starlark doesn't support os.path like python because imports aren't supported.

What's the canonical way to get the parent directory of a string object representing a path in Starlark?

2

There are 2 best solutions below

1
On
load("@bazel_skylib//lib:paths.bzl", "paths")

paths.dirname(path_str)

See https://github.com/bazelbuild/bazel-skylib/blob/main/docs/paths_doc.md

1
On

I can't answer your final question, but hopefully the following will help with the initial problem:

You could use the Label of the target for which this instance of the rule is being built and find its package. This will give you a string representing the parent directory of the BUILD file.

i.e. ctx.label.package