-
Notifications
You must be signed in to change notification settings - Fork 4.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add CurrentRepository() to Python runfiles library #16341
Closed
+222
−2
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
# Copyright 2022 The Bazel Authors. All rights reserved. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
_RUNFILES_CONSTANTS_TEMPLATE = """# Generated by gen_runfiles_constants.bzl | ||
# Internal-only; do no use. | ||
# The name of the runfiles directory corresponding to the main repository. | ||
MAIN_REPOSITORY_RUNFILES_DIRECTORY = '%s' | ||
""" | ||
|
||
def _gen_runfiles_constants_impl(ctx): | ||
out = ctx.actions.declare_file(ctx.attr.name + ".py") | ||
ctx.actions.write(out, _RUNFILES_CONSTANTS_TEMPLATE % ctx.workspace_name) | ||
|
||
return DefaultInfo( | ||
files = depset([out]), | ||
runfiles = ctx.runfiles([out]), | ||
) | ||
|
||
gen_runfiles_constants = rule( | ||
implementation = _gen_runfiles_constants_impl, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,15 @@ | ||
load("//tools/python:gen_runfiles_constants.bzl", "gen_runfiles_constants") | ||
load("//tools/python:private/defs.bzl", "py_library") | ||
|
||
py_library( | ||
name = "runfiles", | ||
srcs = ["runfiles.py"], | ||
srcs = [ | ||
"runfiles.py", | ||
":_runfiles_constants", | ||
], | ||
visibility = ["//visibility:public"], | ||
) | ||
|
||
gen_runfiles_constants( | ||
name = "_runfiles_constants", | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -58,9 +58,12 @@ | |
p = subprocess.Popen([r.Rlocation("path/to/binary")], env, ...) | ||
""" | ||
|
||
import inspect | ||
import os | ||
import posixpath | ||
import sys | ||
|
||
from ._runfiles_constants import MAIN_REPOSITORY_RUNFILES_DIRECTORY | ||
|
||
def CreateManifestBased(manifest_path): | ||
return _Runfiles(_ManifestBased(manifest_path)) | ||
|
@@ -114,6 +117,7 @@ class _Runfiles(object): | |
|
||
def __init__(self, strategy): | ||
self._strategy = strategy | ||
self._python_runfiles_root = _FindPythonRunfilesRoot() | ||
|
||
def Rlocation(self, path): | ||
"""Returns the runtime path of a runfile. | ||
|
@@ -161,6 +165,61 @@ def EnvVars(self): | |
""" | ||
return self._strategy.EnvVars() | ||
|
||
def CurrentRepository(self, frame = 1): | ||
"""Returns the canonical name of the caller's Bazel repository. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's update this doc to point to some bzlmod docs about canonical vs nickname repository names. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done. |
||
|
||
For example, this function returns '' (the empty string) when called from | ||
the main repository and a string of the form 'rules_python~0.13.0` when | ||
called from code in the repository corresponding to the rules_python Bazel | ||
module. | ||
|
||
More information about the difference between canonical repository names and | ||
the `@repo` part of labels is available at: | ||
https://bazel.build/build/bzlmod#repository-names | ||
|
||
NOTE: This function inspects the callstack to determine where in the | ||
runfiles the caller is located to determine which repository it came from. | ||
This may fail or produce incorrect results depending on who the caller is, | ||
for example if it is not represented by a Python source file. Use the | ||
`frame` argument to control the stack lookup. | ||
|
||
Args: | ||
frame: int; the stack frame to return the repository name for. Defaults to | ||
1, the caller of the CurrentRepository function. | ||
Returns: | ||
The canonical name of the Bazel repository containing the file containing | ||
the frame-th caller of this function | ||
Raises: | ||
ValueError: if the caller cannot be determined or the caller's file path | ||
is not contained in the Python runfiles tree | ||
""" | ||
try: | ||
caller_path = inspect.getfile(sys._getframe(frame)) | ||
except (TypeError, ValueError): | ||
raise ValueError("failed to determine caller's file path") | ||
caller_runfiles_path = os.path.relpath(caller_path, self._python_runfiles_root) | ||
if caller_runfiles_path.startswith(".." + os.path.sep): | ||
raise ValueError('{} does not lie under the runfiles root {}'.format(caller_path, self._python_runfiles_root)) | ||
|
||
caller_runfiles_directory = caller_runfiles_path[:caller_runfiles_path.find(os.path.sep)] | ||
if caller_runfiles_directory == MAIN_REPOSITORY_RUNFILES_DIRECTORY: | ||
# The canonical name of the main repository (also known as the workspace) | ||
# is the empty string. | ||
return '' | ||
# For all other repositories, the name of the runfiles directory is the | ||
fmeum marked this conversation as resolved.
Show resolved
Hide resolved
|
||
# canonical name. | ||
return caller_runfiles_directory | ||
|
||
def _FindPythonRunfilesRoot(): | ||
root = __file__ | ||
# Walk up our own runfiles path to the root of the runfiles tree from which | ||
# the current file is being run. This path coincides with what the Bazel | ||
# Python stub sets up as sys.path[0]. Since that entry can be changed at | ||
# runtime, we rederive it here. | ||
for _ in range("bazel_tools/tools/python/runfiles/runfiles.py".count("/") + 1): | ||
root = os.path.dirname(root) | ||
return root | ||
|
||
|
||
class _ManifestBased(object): | ||
"""`Runfiles` strategy that parses a runfiles-manifest to look up runfiles.""" | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Have the caller of the _Runfiles object pass the runfiles directory in as an argument. This avoids most of the issues with trying to re-find the runfiles directory.
In CreateDirectoryBased(), the path can be directly passed in.
In CreateManifestBased(), you can use the same logic the launcher itself uses, which is pretty simple:
https://cs.opensource.google/bazel/bazel/+/master:src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt;l=134-144;drc=c3425feeb3bc204923979773ae985dd2f3e24b9f
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Doing that leads to this test failure: https://storage.googleapis.com/bazel-untrusted-buildkite-artifacts/0183d34f-4545-4f97-933c-3164ea7a67b1/tools%5Cpython%5Crunfiles%5Crunfiles_test%5Ctest.log
Do you know whether there is a convenient way to handle UNC paths in Python?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hm. I think you can simply strip of
\\?
and\\.
. From the docs I've found, it looks like those are special "dos device paths" that refer to the current device, and the difference between\\?
and\\.
is something to do how windows does path normalization.Or maybe check the manifest mapping for the caller's file? _ManifestBased._result has a
runfile_path -> fs path
mapping. If it can be found in there, it's not a big deal to maintain a reverse map.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Did that, but this is now hitting a more fundamental problem (see these logs): The Bazel runfiles root may very well be distinct from the Python runfiles root when using
--build_python_zip
. But the lookup of the current repository should always use the Python runfiles root.The previous approach handled this distinction. Would you be okay with reverting to it?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah, yeah, that's a good point.
How about just looking for ".runfiles" (or the other substrings for the other various cases) in the caller's file path?
I forget what the previous approach was. The module-level _FindRunfilesRoot() function, based upon sys.argv? I could accept that at this point. Not using sys.path, though.
That said, part of the point I'm trying to make here -- one that I'm not really convinced is landing -- is that there just isn't any good way to get the runfiles root after program startup. sys.argv isn't reliable because user code may change it, or it may point to a symlink that points elsewhere. Looking at the callstack is iffy because not all callers have a file, and a caller doesn't necessarily have to live in the runfiles. If we look at all the code surrounding "where is the runfiles root?" (i.e. here and the stub launcher), we see it's very non-trivial with many special cases.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Upfront: Thanks for being diligent and persisting through the review of this arguably weird PR! My situation is really just that we have to make runfiles work as well as possible with the drastic changes that Bzlmod necessarily brings for them. I know this is certainly not ideal and gets us into the fringe parts of the different languages - you don't want to know how we are planning to implement
CurrentRepository
in Java ;-)I preserved it in the first commit: 4b87045#diff-21d70609ca9dc507b2d33f4a68d89bca3cd727191ffe3a6319b63c36e750deb2R215
It's quite similar to scanning for
.runfiles
in the scripts own file path, but slightly more precise since we just know the suffix we need to strip.I do think that it is important to consider the following two aspects of this PR separately. Doing that will also help me understand your point better:
Finding the Python runfiles root:
I don't yet see why this should be difficult: The script at
bazel_tools/tools/py/runfiles/runfiles.py
is an honest Python file and it lies under the runfiles root because the launcher either found the Bazel runfiles directory with this file in the known relative location or set up a runfiles-like directory by extracting the ZIP. Deriving the root from that requires neithersys.argv
norsys.path
, we just strip a suffix from this one particular file's path.This is important because if this part of the runfiles library isn't reliable, the library can't really be used at all.
Using that information to derive the Bazel repository containing the caller:
This is where we invoke a lot of magic that may break in a myriad of ways: It requires investigating the call stack, assumes that the caller is a file, assumes that it lies in the runfiles root, and so on.
Luckily for us, if this magic procedure breaks from a particular location, it's not too bad: It just means that users can't look up their Bazel context from that particular location. Assuming they want to use runfiles, they will likely find some more well-behaved place in their program where the lookup is successful and then pass the repo name on to code that can then call
Rlocation
without any further magic involved.Does this assessment agree with what you are thinking?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, lets just go with that.
It's difficult because (1) the precise layout of the Python side of runfiles is an implementation detail, and (2) Python itself doesn't have an equivalent concept as Bazel's runfiles directory.
The proposed usage of
__file__
assumes the layout is<root>/<repo>/<path>
, but a layout such as e.g.<root>/site-packages/<libname>/<path>
works just as well as far as Python code is concerned.The
__file__
attribute is also optional, so whether it works also depends on how the runfiles library was imported, and the particular details of any custom importer.Stated another way: this runfiles library is only usable for a particular implementation of the Python rules and resulting layout of the files in runfiles. While this may sound innocuous at face value, as a language rule owner, its very unappealing because it means anyone using this runfiles library breaks when we want to change the language rule implementation. Except a user doesn't see "the runfiles library was relying on implementation details", they just see "the language rules changed and broke me".
I consider the "they can just pick another location to call their code" assumption a weak one. It assumes the person who picks the path is also the one that calls the runfiles APIs. This assumption breaks down because people like to build libraries. For example, a Django plugin that inherently understood runfiles. Such a case has a user specifying paths, while the actual runfiles API call is done by e.g. django code.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I dropped the last commit, so we are now back to this.
I agree that's not a good situation, in particular because you didn't ask for this feature. I can at least promise that if you ever want to change the runfiles layout used by the Python rules, you can ping me and I will adapt this library as needed.
As long as the runfiles library remains coupled to the source of truth for the python rules, such breakages should at least be detected by the test I added. If anybody copies the runfiles library somewhere other than
@bazel_tools//tools/runfiles/python
and imports them in a different way without making the necessary changes, they would be on their own.I think that the hypothetical Django plugin could, similar to how
Rlocation
will be adapated, receive an optional repository name argument that, if provided, is used as context instead of the magicCurrentRepository()
. That would again put the user in control.