在 bazel 规则中执行 native_binary

Executing a native_binary inside a bazel rule

@bazel_skylib//rules:native_binary.bzl 定义了 native_binary 规则,可用于将本机可执行文件包装在 bazel 目标中。我用它来包装一个来自 Sciter SDK 的名为 packfolder.exe 的打包工具。

我将二进制文件放入 third_party/sciter/packfolder.exe 的源代码树中,并编写了这个 BUILD 文件。

# third_party/sciter/BUILD
native_binary(name = "packfolder",
              src = "packfolder.exe",
              out = "packfolder.exe"
)

bazel run third_party/sciter:packfolder 运行没有问题。现在我想在我的自定义 cc_sciter_resource 规则中使用这个目标。

# third_party/sciter/sciter_rules.bzl

def _impl(ctx):
    in_files = ctx.files.srcs
    output_file = ctx.actions.declare_file(ctx.label.name)
    ctx.actions.run(
        outputs = [output_file],
        inputs = in_files,
        arguments = [],
        executable = ctx.executable.packfolder.path)
    return DefaultInfo(files = depset([output_file]))

cc_sciter_resource = rule(
    implementation = _impl,
    attrs = {
        "srcs": attr.label_list(),
        "packfolder": attr.label(
            default = Label("//third_party/sciter:packfolder"),
            executable = True,
            cfg = "exec"
        ),        
    }
)

麻烦的是,当我尝试构建一个使用此规则的目标时,说

cc_sciter_resource(
    name = "hello_world_resource.cpp"
    srcs = [...]
)

我收到以下错误。

ERROR: C:/users/marki/sciter-bazel/examples/BUILD:12:19: Action examples/hello_world_resource.cpp failed (Exit -1): packfolder.exe failed: error executing command
  cd C:/users/marki/_bazel_marki/kiodv2fz/execroot/sciter_bazel
bazel-out/x64_windows-opt-exec-2B5CBBC6/bin/third_party/sciter/packfolder.exe
Execution platform: @local_config_platform//:host. Note: Remote connection/protocol failed with: execution failed
Action failed to execute: java.io.IOException: ERROR: src/main/native/windows/process.cc(202): CreateProcessW("C:\users\marki\_bazel_marki\kiodv2fz\execroot\sciter_bazel\bazel-out\x64_windows-opt-exec-2B5CBBC6\bin\third_party\sciter\packfolder.exe"): The system cannot find the file specified.
 (error: 2)
Target //examples:hello_world_resource.cpp failed to build

目录 C:\users\marki\_bazel_marki\kiodv2fz\execroot\sciter_bazel\bazel-out\x64_windows-opt-exec-2B5CBBC6 在我的电脑上不存在。所以错误是准确的,但我不知道如何解决这个问题。

--- sciter_rules.bzl
+++ sciter_rules.bzl
@@ -6,7 +6,7 @@
         outputs = [output_file],
         inputs = in_files,
         arguments = [],
-        executable = ctx.executable.packfolder.path)
+        executable = ctx.executable.packfolder)
     return DefaultInfo(files = depset([output_file]))
 
 cc_sciter_resource = rule(

ctx.executable.packfolder.path 只是一个字符串,所以 Bazel 不知道 packfolder 可执行文件需要添加为操作的输入。