天天看點

Bazel - 8(外部Bazel項目依賴 - http_archive)

作者:心動不凍

上文我們使用了git_repository,Bazel可以直接從github下載下傳指定的外部依賴庫,非常友善。不過,需要你的系統裡安裝git,這個要求對于那些使用其他版本控制軟體,如svn的人來說該怎麼辦呢?Bazel提供了http_archive,你可以把某個Bazel項目repository打包壓縮成一個檔案。

咱們先建立這個Bazel項目repository,還是老規矩,hello-world-lib。

Bazel - 8(外部Bazel項目依賴 - http_archive)

hello-world-lib/BUILD

load("@rules_cc//cc:defs.bzl", "cc_library")

cc_library(
    name = "hello-world-lib",
    srcs = ["src/hello-world.cc"],
    hdrs = ["include/hello-world.h"],
    visibility = ["//visibility:public"],
)           

hello-world-lib/include/hello-world.h

#pragma once

#include <string>

std::string hello_world();           

hello-world-lib/src/hello-world.cc

#include "include/hello-world.h"

std::string hello_world() { return "Hello, world!"; }           

打開終端,将目前目錄切換到hello-world-lib,運作:tar -zcvf hello-world.tar.gz *

這樣我們将hello-world-lib中的兩個檔案和兩個檔案夾打包壓縮成了一個檔案,然後我把它上傳到了我的個人網站上(bazel-learning.zhouxd.com),不過你可能不一定能夠通路到這個url,你可以放到你自己的網站上。Bazel會自動解析url,下載下傳并解壓這個檔案,将裡面的内容建構成一個repository。

好了,我們再次建立一個Bazel項目來使用它。

Bazel - 8(外部Bazel項目依賴 - http_archive)

hello-world-http-archive/WORKSPACE

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "hello-world-repo",
    urls = ["file:/home/zhouxd/temp/hello-world-archive/hello-world.tar.gz",
            "https://bazel-learning.zhouxd.com/hello-world.tar.gz"],
)           

這裡urls我給了兩個,防止萬一我的網站挂了,還可以從本地的壓縮包中完成建構。多說一點,如果你得到的某個外部項目的壓縮封包件的目錄結構,WORKSPACE并不在頂級目錄中,而是在某個目錄下,比如說放在了hello-world-lib-1.2.3裡面,你可以使用strip_prefix屬性來指定略過這個目錄名。

http_archive(
    name = "hello-world-repo",
    urls = ["file:/home/zhouxd/temp/hello-world-archive/hello-world.tar.gz",
            "https://bazel-learning.zhouxd.com/hello-world.tar.gz"],
    strip_prefix = "hello-world-lib.1.2.3",
)           

為了確定壓縮包的資料完整性,還可以通過sha256這個屬性來指定壓縮包的簽名。如果你懶得用openssl來生成這個簽名,用Bazel建構時它會告訴你這個壓縮包的簽名,你把它複制下來,然後添加sha256屬性,其值設定為這個字元串就可以了。

Bazel - 8(外部Bazel項目依賴 - http_archive)

hello-world-http-archive/src/BUILD

load("@rules_cc//cc:defs.bzl", "cc_binary")

cc_binary(
    name = "hello-world-main",
    srcs = ["hello-world-main.cc"],
    deps = [
        "@hello-world-repo//:hello-world-lib",
    ],
)           

hello-world-http-archive/src/hello-world-main.cc

#include "include/hello-world.h"
#include <iostream>

int main() {
  std::cout << hello_world() << std::endl;
  return 0;
}           

建構,運作!

Bazel - 8(外部Bazel項目依賴 - http_archive)

源碼擷取:https://github.com/zhouxindong/bazel-learning.git

繼續閱讀