如何创建使用另一个规则的运行文件路径的自定义 bazel 构建规则?

How can I create a custom bazel build rule that uses the runfiles path of another rule?

我正在尝试创建自定义构建规则以从 py_binary 输出构建 pip 包。要创建我的 pip 包,我想调用一个 shell 脚本。 shell 脚本通过从 py_binary 输出的运行文件创建一个 zip 文件来构建一个 pip 包。

例如假设我有

py_binary(
    name = "some_binary",
    srcs = ["some_binary.py"],
    srcs_version = "PY2AND3",
)

构建此规则会产生

bazel-bin/some_binary.runfiles

我现在想创建一个自定义构建规则,它将调用我的 shell 脚本,位置为 bazel-bin/some_binary.runfiles

我尝试创建一个宏

def build_pip_package(
    name, py_binary=None, setup_file=None):
  """Create a pip package from a py_binary.

  The source file should be a text file with python formatting i.e.

  Args:
    name: Name for the rule.
    py_binary: Build rule producing the py_binary
    setup_file: Build rule producing the setup.py file to use to produce
      the package.
  """
  output= "somefile"
  native.genrule(
      name=name,
      outs=[output],
      cmd="echo $(location //:build_pip_package_script) "
      + "--py_runfiles_path=$(locations %s)" % py_binary
      + " --setup_file=$(location %s) " % setup_file,
      tools=["//:build_pip_package_script"],
      srcs=[setup_file, py_binary])

这最终会用

调用我的 shell 脚本
bazel-out/local-fastbuild/bin/some_binary/model_train some_binary.py 

如何使用与 some_binary 目标对应的 runfiles 目录的位置调用我的脚本。

如果您将 py_binary 放在工具属性而不是 srcs 中,bazel 将包含运行文件树。您可以通过 "$(location %s).runfiles" % py_binary

访问它