使用Bazel拉GitHub存储库

时间:2018-05-29 20:59:39

标签: github bazel

我需要使用Bazel下载整个GitHub存储库。由于我对这个工具很陌生,所以我不确定如何实现这个目标。

我的主要想法是:

downloadgithubrepo.bzl (位于项目根目录中,就像WORKSPACE文件一样)编写自定义存储库规则,例如:

def _impl(repository_ctx):
    repository_ctx.download("url_to_zipped_github_repo", output='relative_path_to_output_file')

github = repository_rule(
    implementation = _impl

并在 WORKSPACE 文件中编写如下内容:

load("//:downloadgithubrepo.bzl", "github")

并且需要调用构建 BUILD 文件(也位于项目根目录下) 其内容如下:

cc_library(
    name = "testrun",
    srcs = "main.c",
)

我不得不添加main.c文件,否则构建失败 - 这是一个问题,真正的问题是这不起作用,因为在构建中传递但是没有下载GitHub存储库。

我是否走在正确的道路上?有没有人以前做过这样的事情?

1 个答案:

答案 0 :(得分:4)

如果GitHub项目已连接了Bazel BUILD文件,那么您在new_git_repository存储库规则或git_repository规则中可能已经实现了什么。

如果GitHub项目具有BUILD文件,则在使用new_git_repository时需要BUILD文件。例如,如果您想依赖https://github.com/example/repository中的file target (e.g. /foo/bar.txt) or rule target (e.g. a cc_library),并且存储库 没有构建BUILD文件,请在项目的WORKSPACE文件中写下这些行:

new_git_repository(
    name = "example_repository",
    remote = "https://github.com/example/repository.git",
    build_file_content = """
exports_files(["foo/bar.txt"])

# you can also create targets
cc_library(
    name = "remote_cc_library",
    srcs = ["..."],
    hdrs = ["..."],
""",
)

BUILD文件中,使用@前缀引用外部存储库的目标:

cc_library(
    name = "testrun",
    srcs = ["main.c"],
    data = ["@example_repository//:foo/bar.txt"],
    deps = ["@example_repository//:remote_cc_library"],
)

当你运行bazel build //:testrun时,Bazel会......

  1. 分析//:testrun的依赖关系,其中包含文件main.c和来自外部存储库@example_repository的目标。
  2. 在WORKSPACE文件中查找名为example_repository的外部存储库,并找到new_git_repository声明。
  3. git clone声明中指定的remote属性执行example_repository
  4. 在克隆存储库的项目根目录中编写包含build_file_content字符串的BUILD文件。
  5. 分析目标@example_repository//:foo/bar.txt@example_repository//:remote_cc_library
  6. 构建依赖关系,并将其移交给//:testrun cc_library
  7. 构建//:testrun
  8. 如果GitHub项目具有 BUILD文件,则无需提供BUILD文件。在使用git_repository指定WORKSPACE依赖关系后,您可以直接引用目标:

    git_repository(
        name = "example_repository",
        remote = "https://github.com/example/repository.git",
    )
    

    有关更多信息,请查看Bazel关于External Repositories的文档。