Bazel:相对本地路径作为 http_archive() 中的 url

7 c++ bazel

我正在尝试将外部库包含到我的 Bazel 项目中。它是一个商业、闭源软件库,以tar 文件 (Linux) 中的一堆.h和文件形式出现。.a没有公共下载链接,您必须在某处手动下载存档。

因此,我将库档案签入 Git(我们不在这里讨论这个)并vendor/使用

http_archive(
    name = "library_name",
    build_file = "//third_party:library_name.BUILD",
    sha256 = "12165fbcbac............",
    urls = ["file:///home/myuser/git/repo/vendor/libraryname.tar.gz"],
)
Run Code Online (Sandbox Code Playgroud)

我不想在 中使用绝对路径urls=,这样我的同事就可以轻松地签出并构建库。如何使用相对路径http_archive()

我看过这个答案,但似乎不是完全相同的问题,而且示例不完整。

Bri*_*man 5

一个非常简单的自定义存储库规则就可以为您做到这一点。repository_ctx.extract完成所有繁重的工作。我刚才写了这个作为一个简单的例子:

def _test_archive_impl(repository_ctx):
  repository_ctx.extract(repository_ctx.attr.src)
  repository_ctx.file("BUILD.bazel", repository_ctx.read(repository_ctx.attr.build_file))

test_archive = repository_rule(
    attrs = {
        "src": attr.label(mandatory = True, allow_single_file = True),
        "build_file": attr.label(mandatory = True, allow_single_file = True),
    },
    implementation = _test_archive_impl,
)
Run Code Online (Sandbox Code Playgroud)

对于您的基本用例,您可能不需要对其进行任何更改(除了更好的名称)。添加传递stripPrefix 的功能将很简单。根据您的用例,build_file_contents像其他规则一样build_file可能也很有用。

作为参考,这是WORKSPACE我用于测试的(上面的规则定义位于test.bzl):

load("//:test.bzl", "test_archive")

test_archive(
    name = "test_repository",
    src = "//:test.tar.gz",
    build_file = "//:test.BUILD",
)
Run Code Online (Sandbox Code Playgroud)

作为所有这些的替代方法,您可以只从存档中签入文件,然后使用new_local_repository代替。在某些方面更容易合作,在其他方面则更困难。