Build Bazel package from multiple repos

Viewed 576

I am trying to build OpenCV with external modules, but haven't been able to come up with a clean solution.

I have successfully built OpenCV using CMake (rules_foreign_cc). But to be able to build with external modules I need to download a separate repo (opencv_contrib) and then build using the path to the second repo as a build argument.

Is there a way I can do this without having to create a git repo of my own that combines these two git repos?

2 Answers
# WORKSPACE file

http_archive(
   name = "rules_foreign_cc",
   strip_prefix = "rules_foreign_cc-4010620160e0df4d894b61496d3d3b6fc8323212",
    sha256 = "07e3414cc841b1f4d16e5231eb818e5c5e03e2045827f5306a55709e5045c7fd",
   url = "https://github.com/bazelbuild/rules_foreign_cc/archive/4010620160e0df4d894b61496d3d3b6fc8323212.zip",
)

load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies")
rules_foreign_cc_dependencies()


http_archive(
    name = "opencv_contrib",
    build_file="//:opencv_contrib.BUILD",
    sha256 = "9f52fd3114ac464cb4c9a2a6a485c729a223afb57b9c24848484e55cef0b5c2a",
    urls = ["https://github.com/opencv/opencv_contrib/archive/refs/tags/4.5.2.tar.gz"],
    strip_prefix = "opencv_contrib-4.5.2",
)

http_archive(
    name = "opencv",
    sha256="ae258ed50aa039279c3d36afdea5c6ecf762515836b27871a8957c610d0424f8",
    build_file="//:opencv.BUILD",
    urls = ["https://github.com/opencv/opencv/archive/refs/tags/4.5.2.tar.gz"],
    strip_prefix = "opencv-4.5.2",
)

# opencv_contrib.BUILD file

filegroup(
    name = "modules",
    srcs = glob(["modules/**"]),
    visibility = ["//visibility:public"],
)
# opencv.BUILD file

load("@rules_foreign_cc//foreign_cc:defs.bzl", "cmake")

filegroup(
    name = "srcs",
    srcs = glob(["**"]),
    visibility = ["//visibility:public"],
)
cmake(
    name = "opencv",
    generate_args = ["-GNinja"],
    additional_inputs=["@opencv_contrib//:modules"],
    cache_entries = {
        "BUILD_SHARED_LIBS": "OFF",
        "BUILD_opencv_world": "ON",
        "OPENCV_EXTRA_MODULES_PATH": "$$EXT_BUILD_ROOT$$/external/opencv_contrib/modules",
    },
    lib_source = ":srcs",
    out_static_libs = ["libopencv_world.a"],
)

You can use git_repository rule in your WORKSPACE file to have bazel automatically clone a git repo before building.

Once you add it to the WORKSPACE file, then you can reference build targets of the remote repo inside your own repo.

Check this repo for an example.

Related