|
| 1 | +# Copyright 2018 The Bazel Authors. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +############################################################################### |
| 16 | +# Vendored in from bazelbuild/bazel (tools/python/runfiles/runfiles.py) at # |
| 17 | +# commit 6c60a8ec049b6b8540c473969dd7bd1dad46acb9 (2019-07-19). See # |
| 18 | +# //python/runfiles:BUILD for details. # |
| 19 | +############################################################################### |
| 20 | + |
| 21 | +"""Runfiles lookup library for Bazel-built Python binaries and tests. |
| 22 | +
|
| 23 | +USAGE: |
| 24 | +
|
| 25 | +1. Depend on this runfiles library from your build rule: |
| 26 | +
|
| 27 | + py_binary( |
| 28 | + name = "my_binary", |
| 29 | + ... |
| 30 | + deps = ["@bazel_tools//tools/python/runfiles"], |
| 31 | + ) |
| 32 | +
|
| 33 | +2. Import the runfiles library. |
| 34 | +
|
| 35 | + from bazel_tools.tools.python.runfiles import runfiles |
| 36 | +
|
| 37 | +3. Create a Runfiles object and use rlocation to look up runfile paths: |
| 38 | +
|
| 39 | + r = runfiles.Create() |
| 40 | + ... |
| 41 | + with open(r.Rlocation("my_workspace/path/to/my/data.txt"), "r") as f: |
| 42 | + contents = f.readlines() |
| 43 | + ... |
| 44 | +
|
| 45 | + The code above creates a manifest- or directory-based implementations based |
| 46 | + on the environment variables in os.environ. See `Create()` for more info. |
| 47 | +
|
| 48 | + If you want to explicitly create a manifest- or directory-based |
| 49 | + implementations, you can do so as follows: |
| 50 | +
|
| 51 | + r1 = runfiles.CreateManifestBased("path/to/foo.runfiles_manifest") |
| 52 | +
|
| 53 | + r2 = runfiles.CreateDirectoryBased("path/to/foo.runfiles/") |
| 54 | +
|
| 55 | + If you want to start subprocesses that also need runfiles, you need to set |
| 56 | + the right environment variables for them: |
| 57 | +
|
| 58 | + import subprocess |
| 59 | + from bazel_tools.tools.python.runfiles import runfiles |
| 60 | +
|
| 61 | + r = runfiles.Create() |
| 62 | + env = {} |
| 63 | + ... |
| 64 | + env.update(r.EnvVars()) |
| 65 | + p = subprocess.Popen([r.Rlocation("path/to/binary")], env, ...) |
| 66 | +""" |
| 67 | + |
| 68 | +import os |
| 69 | +import posixpath |
| 70 | + |
| 71 | + |
| 72 | +def CreateManifestBased(manifest_path): |
| 73 | + return _Runfiles(_ManifestBased(manifest_path)) |
| 74 | + |
| 75 | + |
| 76 | +def CreateDirectoryBased(runfiles_dir_path): |
| 77 | + return _Runfiles(_DirectoryBased(runfiles_dir_path)) |
| 78 | + |
| 79 | + |
| 80 | +def Create(env=None): |
| 81 | + """Returns a new `Runfiles` instance. |
| 82 | +
|
| 83 | + The returned object is either: |
| 84 | + - manifest-based, meaning it looks up runfile paths from a manifest file, or |
| 85 | + - directory-based, meaning it looks up runfile paths under a given directory |
| 86 | + path |
| 87 | +
|
| 88 | + If `env` contains "RUNFILES_MANIFEST_FILE" with non-empty value, this method |
| 89 | + returns a manifest-based implementation. The object eagerly reads and caches |
| 90 | + the whole manifest file upon instantiation; this may be relevant for |
| 91 | + performance consideration. |
| 92 | +
|
| 93 | + Otherwise, if `env` contains "RUNFILES_DIR" with non-empty value (checked in |
| 94 | + this priority order), this method returns a directory-based implementation. |
| 95 | +
|
| 96 | + If neither cases apply, this method returns null. |
| 97 | +
|
| 98 | + Args: |
| 99 | + env: {string: string}; optional; the map of environment variables. If None, |
| 100 | + this function uses the environment variable map of this process. |
| 101 | + Raises: |
| 102 | + IOError: if some IO error occurs. |
| 103 | + """ |
| 104 | + env_map = os.environ if env is None else env |
| 105 | + manifest = env_map.get("RUNFILES_MANIFEST_FILE") |
| 106 | + if manifest: |
| 107 | + return CreateManifestBased(manifest) |
| 108 | + |
| 109 | + directory = env_map.get("RUNFILES_DIR") |
| 110 | + if directory: |
| 111 | + return CreateDirectoryBased(directory) |
| 112 | + |
| 113 | + return None |
| 114 | + |
| 115 | + |
| 116 | +class _Runfiles(object): |
| 117 | + """Returns the runtime location of runfiles. |
| 118 | +
|
| 119 | + Runfiles are data-dependencies of Bazel-built binaries and tests. |
| 120 | + """ |
| 121 | + |
| 122 | + def __init__(self, strategy): |
| 123 | + self._strategy = strategy |
| 124 | + |
| 125 | + def Rlocation(self, path): |
| 126 | + """Returns the runtime path of a runfile. |
| 127 | +
|
| 128 | + Runfiles are data-dependencies of Bazel-built binaries and tests. |
| 129 | +
|
| 130 | + The returned path may not be valid. The caller should check the path's |
| 131 | + validity and that the path exists. |
| 132 | +
|
| 133 | + The function may return None. In that case the caller can be sure that the |
| 134 | + rule does not know about this data-dependency. |
| 135 | +
|
| 136 | + Args: |
| 137 | + path: string; runfiles-root-relative path of the runfile |
| 138 | + Returns: |
| 139 | + the path to the runfile, which the caller should check for existence, or |
| 140 | + None if the method doesn't know about this runfile |
| 141 | + Raises: |
| 142 | + TypeError: if `path` is not a string |
| 143 | + ValueError: if `path` is None or empty, or it's absolute or not normalized |
| 144 | + """ |
| 145 | + if not path: |
| 146 | + raise ValueError() |
| 147 | + if not isinstance(path, str): |
| 148 | + raise TypeError() |
| 149 | + if (path.startswith("../") or "/.." in path or path.startswith("./") or |
| 150 | + "/./" in path or path.endswith("/.") or "//" in path): |
| 151 | + raise ValueError("path is not normalized: \"%s\"" % path) |
| 152 | + if path[0] == "\\": |
| 153 | + raise ValueError("path is absolute without a drive letter: \"%s\"" % path) |
| 154 | + if os.path.isabs(path): |
| 155 | + return path |
| 156 | + return self._strategy.RlocationChecked(path) |
| 157 | + |
| 158 | + def EnvVars(self): |
| 159 | + """Returns environment variables for subprocesses. |
| 160 | +
|
| 161 | + The caller should set the returned key-value pairs in the environment of |
| 162 | + subprocesses in case those subprocesses are also Bazel-built binaries that |
| 163 | + need to use runfiles. |
| 164 | +
|
| 165 | + Returns: |
| 166 | + {string: string}; a dict; keys are environment variable names, values are |
| 167 | + the values for these environment variables |
| 168 | + """ |
| 169 | + return self._strategy.EnvVars() |
| 170 | + |
| 171 | + |
| 172 | +class _ManifestBased(object): |
| 173 | + """`Runfiles` strategy that parses a runfiles-manifest to look up runfiles.""" |
| 174 | + |
| 175 | + def __init__(self, path): |
| 176 | + if not path: |
| 177 | + raise ValueError() |
| 178 | + if not isinstance(path, str): |
| 179 | + raise TypeError() |
| 180 | + self._path = path |
| 181 | + self._runfiles = _ManifestBased._LoadRunfiles(path) |
| 182 | + |
| 183 | + def RlocationChecked(self, path): |
| 184 | + return self._runfiles.get(path) |
| 185 | + |
| 186 | + @staticmethod |
| 187 | + def _LoadRunfiles(path): |
| 188 | + """Loads the runfiles manifest.""" |
| 189 | + result = {} |
| 190 | + with open(path, "r") as f: |
| 191 | + for line in f: |
| 192 | + line = line.strip() |
| 193 | + if line: |
| 194 | + tokens = line.split(" ", 1) |
| 195 | + if len(tokens) == 1: |
| 196 | + result[line] = line |
| 197 | + else: |
| 198 | + result[tokens[0]] = tokens[1] |
| 199 | + return result |
| 200 | + |
| 201 | + def _GetRunfilesDir(self): |
| 202 | + if self._path.endswith("/MANIFEST") or self._path.endswith("\\MANIFEST"): |
| 203 | + return self._path[:-len("/MANIFEST")] |
| 204 | + elif self._path.endswith(".runfiles_manifest"): |
| 205 | + return self._path[:-len("_manifest")] |
| 206 | + else: |
| 207 | + return "" |
| 208 | + |
| 209 | + def EnvVars(self): |
| 210 | + directory = self._GetRunfilesDir() |
| 211 | + return { |
| 212 | + "RUNFILES_MANIFEST_FILE": self._path, |
| 213 | + "RUNFILES_DIR": directory, |
| 214 | + # TODO(laszlocsomor): remove JAVA_RUNFILES once the Java launcher can |
| 215 | + # pick up RUNFILES_DIR. |
| 216 | + "JAVA_RUNFILES": directory, |
| 217 | + } |
| 218 | + |
| 219 | + |
| 220 | +class _DirectoryBased(object): |
| 221 | + """`Runfiles` strategy that appends runfiles paths to the runfiles root.""" |
| 222 | + |
| 223 | + def __init__(self, path): |
| 224 | + if not path: |
| 225 | + raise ValueError() |
| 226 | + if not isinstance(path, str): |
| 227 | + raise TypeError() |
| 228 | + self._runfiles_root = path |
| 229 | + |
| 230 | + def RlocationChecked(self, path): |
| 231 | + # Use posixpath instead of os.path, because Bazel only creates a runfiles |
| 232 | + # tree on Unix platforms, so `Create()` will only create a directory-based |
| 233 | + # runfiles strategy on those platforms. |
| 234 | + return posixpath.join(self._runfiles_root, path) |
| 235 | + |
| 236 | + def EnvVars(self): |
| 237 | + return { |
| 238 | + "RUNFILES_DIR": self._runfiles_root, |
| 239 | + # TODO(laszlocsomor): remove JAVA_RUNFILES once the Java launcher can |
| 240 | + # pick up RUNFILES_DIR. |
| 241 | + "JAVA_RUNFILES": self._runfiles_root, |
| 242 | + } |
| 243 | + |
| 244 | + |
| 245 | +def _PathsFrom(argv0, runfiles_mf, runfiles_dir, is_runfiles_manifest, |
| 246 | + is_runfiles_directory): |
| 247 | + """Discover runfiles manifest and runfiles directory paths. |
| 248 | +
|
| 249 | + Args: |
| 250 | + argv0: string; the value of sys.argv[0] |
| 251 | + runfiles_mf: string; the value of the RUNFILES_MANIFEST_FILE environment |
| 252 | + variable |
| 253 | + runfiles_dir: string; the value of the RUNFILES_DIR environment variable |
| 254 | + is_runfiles_manifest: lambda(string):bool; returns true if the argument is |
| 255 | + the path of a runfiles manifest file |
| 256 | + is_runfiles_directory: lambda(string):bool; returns true if the argument is |
| 257 | + the path of a runfiles directory |
| 258 | +
|
| 259 | + Returns: |
| 260 | + (string, string) pair, first element is the path to the runfiles manifest, |
| 261 | + second element is the path to the runfiles directory. If the first element |
| 262 | + is non-empty, then is_runfiles_manifest returns true for it. Same goes for |
| 263 | + the second element and is_runfiles_directory respectively. If both elements |
| 264 | + are empty, then this function could not find a manifest or directory for |
| 265 | + which is_runfiles_manifest or is_runfiles_directory returns true. |
| 266 | + """ |
| 267 | + mf_alid = is_runfiles_manifest(runfiles_mf) |
| 268 | + dir_valid = is_runfiles_directory(runfiles_dir) |
| 269 | + |
| 270 | + if not mf_alid and not dir_valid: |
| 271 | + runfiles_mf = argv0 + ".runfiles/MANIFEST" |
| 272 | + runfiles_dir = argv0 + ".runfiles" |
| 273 | + mf_alid = is_runfiles_manifest(runfiles_mf) |
| 274 | + dir_valid = is_runfiles_directory(runfiles_dir) |
| 275 | + if not mf_alid: |
| 276 | + runfiles_mf = argv0 + ".runfiles_manifest" |
| 277 | + mf_alid = is_runfiles_manifest(runfiles_mf) |
| 278 | + |
| 279 | + if not mf_alid and not dir_valid: |
| 280 | + return ("", "") |
| 281 | + |
| 282 | + if not mf_alid: |
| 283 | + runfiles_mf = runfiles_dir + "/MANIFEST" |
| 284 | + mf_alid = is_runfiles_manifest(runfiles_mf) |
| 285 | + if not mf_alid: |
| 286 | + runfiles_mf = runfiles_dir + "_manifest" |
| 287 | + mf_alid = is_runfiles_manifest(runfiles_mf) |
| 288 | + |
| 289 | + if not dir_valid: |
| 290 | + runfiles_dir = runfiles_mf[:-9] # "_manifest" or "/MANIFEST" |
| 291 | + dir_valid = is_runfiles_directory(runfiles_dir) |
| 292 | + |
| 293 | + return (runfiles_mf if mf_alid else "", runfiles_dir if dir_valid else "") |
0 commit comments