bazelskylark

How to create a directory structure in bazel


I want to create the following structure in bazel.

dir1
   |_ file1
   |_ file2
   |_ dir2
         |_file3

Creating a specific structure doesn't seem trivial. I'm hoping there's a simple and reusable rule. Something like:

makedir(
  name = "dir1",
  path = "dir1",
)

makedir(
  name = "dir2",
  path = "dir1/dir2",
  deps = [":dir1"],
)

What I've tried:

The use case is that I want to create a squashfs using bazel.

It's important to note that Bazel provides some packaging functions.

To create a squashfs, the command requires a directory structure populated with artifacts.


Solution

  • In my case, I want to create a directory structure and run mksquashfs to produce a squashfs file.

    To accomplish this, I ended up modifying the basic example from bazel's docs on packaging.

    load("@bazel_tools//tools/build_defs/pkg:pkg.bzl", "pkg_tar")
    
    genrule(
        name = "file1",
        outs = ["file1.txt"],
        cmd = "echo exampleText > $@",
    )
    
    pkg_tar(
        name = "dir1",
        strip_prefix = ".",
        package_dir = "/usr/bin",
        srcs = [":file1"],
        mode = "0755",
    )
    
    pkg_tar(
        name = "dir2",
        strip_prefix = ".",
        package_dir = "/usr/share",
        srcs = ["//main:file2.txt", "//main:file3.txt"],
        mode = "0644",
    )
    
    pkg_tar(
        name = "pkg",
        extension = "tar.gz",
        deps = [
            ":dir1",
            ":dir2",
        ],
    )
    

    If there's an easier way to create a tar or directory structure without the need for intermediate tars, I'll make that top answer.