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

Bazel: relative local path as url in http_archive()

本文关键字:url 相对 路径 http archive Bazel      更新时间:2023-10-16

我正试图在我的Bazel项目中包含一个外部库。它是一个商业的闭源代码软件库,在tar文件(Linux(中由一堆.h.a文件组成。没有公共下载链接,您必须在某个地方手动下载存档。

因此,我在vendor/中将库档案检查到Git中(这里不讨论(,并使用

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

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

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

一个非常简单的自定义存储库规则可以为您做到这一点。repositoryctx.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,
)

对于您的基本用例,您可能不需要对此进行任何更改(除了一个更好的名称(。添加通过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",
)

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