How to patch additional build commands to third party CMake-only library built within BAZEL project?

106 views Asked by At

I want to use one third party library in my bazel project. As of today, library is buildable only with CMake system. I am fetching the source code of the library via http_archive rule, and building it in my project using cmake rule of rules_foreign_cc. Since the library is compatible only with cmake, so I think that is the fastest way to build it within bazel project, without modifying anything. My build is failing, because it complains that there is no cmake_minimum_required specified in CMakeLists.txt of third party library. How can I somehow patch on the fly this additional line to remote CMakeLists.txt? Is there a way?

I am fetching it something like this:

http_archive(
    name = "third_party_cmake_lib",
    build_file_content = all_content,
    strip_prefix = "prefix",
    urls = ["https://github.com/third_party_cmake_lib"],
)

And in a bazel BUILD file of my project simply:

load("@rules_foreign_cc//foreign_cc:cmake.bzl", "cmake") 
cmake( 
    name = "third_party_lib", 
    generate_args = ["-GNinja"], 
    lib_source = "@third_party_lib//:all", 
    out_static_libs = ["libthird_party_lib.a"], )

Can I somehow set cmake_minimum_required in bazel BUILD file and tell it to patch it to the third party library's CMakeLists.txt? Thanks in advance.

1

There are 1 answers

0
Vertexwahn On

Make use of patch_cmd attribute of the http_archive rule.

The attribute patch_cmds of the http_archive rule can be used to execute some random shell commands. This can be used to move files from a subdirectory to the root directory or any other changes you want to apply (e.g. adding minimum CMake version):

You can also have different commands for a Windows build using patch_cmds_win:

http_archive(
    name = "fmt",
    ...
    patch_cmds = [
        "mv support/bazel/.bazelrc .bazelrc",
        "mv support/bazel/.bazelversion .bazelversion",
        "mv support/bazel/BUILD.bazel BUILD.bazel",
        "mv support/bazel/WORKSPACE.bazel WORKSPACE.bazel",
    ],
    # Windows-related patch commands are only needed in the case MSYS2 is not installed
    patch_cmds_win = [
        "Move-Item -Path support/bazel/.bazelrc -Destination .bazelrc",
        "Move-Item -Path support/bazel/.bazelversion -Destination .bazelversion",
        "Move-Item -Path support/bazel/BUILD.bazel -Destination BUILD.bazel",
        "Move-Item -Path support/bazel/WORKSPACE.bazel -Destination WORKSPACE.bazel",
    ],
    ...
)

Search for patch on this site to get more information about the different options to patch an existing archive.