Search code examples
bazel

How bazel genrule srcs works under the hood


Well, I'm trying to figure out how srcs works for genrule, I have the following:

genrule(
    name = "flutter_build_android",
     srcs = [
        "//:genfiles"
    ],
    outs = ["android/mobile.apk"],
    cmd_bash = "ls -ltr && flutter build apk > $@",
    tags = ["local"]
)

//:genfiles is a filegroup using glob:

filegroup(
    name = "genfiles",
    srcs = glob(["lib/**","assets/**", "pubspec.yaml"])
)

When executing my genrule what I expect is only files under ://genfiles label should be returned, but it is returning all folders under my root project:

enter image description here


Solution

  • What's happening is that the genrule is tagged with local, and local means

    precludes the action or test from being remotely cached, remotely executed, or run inside the sandbox
    

    https://bazel.build/reference/be/common-definitions#common.tags

    Sandboxing is what prevents an action from seeing files that aren't declared as dependencies (i.e. in srcs here). Without the sandbox, the action sees everything.

    $ tree
    .
    ├── BUILD
    ├── file1
    ├── file2
    ├── file3
    └── WORKSPACE
    
    0 directories, 5 files
    
    $ cat BUILD
    
    genrule(
      name = "gen_foo",
      outs = ["foo"],
      srcs = ["file1"],
      cmd = "echo ----- ; ls ; echo ----- ; wc -l $< > $@",
      # tags = ["local"],
    )
    
    $ bazel build foo
    INFO: Analyzed target //:foo (5 packages loaded, 9 targets configured).
    INFO: Found 1 target...
    INFO: From Executing genrule //:gen_foo:
    -----
    bazel-out
    external
    file1
    -----
    Target //:foo up-to-date:
      bazel-bin/foo
    INFO: Elapsed time: 0.379s, Critical Path: 0.02s
    INFO: 2 processes: 1 internal, 1 linux-sandbox.
    INFO: Build completed successfully, 2 total actions
    
    # edit BUILD to restore the local tag
    
    $ cat BUILD
    
    genrule(
      name = "gen_foo",
      outs = ["foo"],
      srcs = ["file1"],
      cmd = "echo ----- ; ls ; echo ----- ; wc -l $< > $@",
      tags = ["local"],
    )
    
    $ bazel build foo
    INFO: Analyzed target //:foo (5 packages loaded, 9 targets configured).
    INFO: Found 1 target...
    INFO: From Executing genrule //:gen_foo:
    -----
    BUILD
    WORKSPACE
    bazel-out
    external
    file1
    file2
    file3
    local-spawn-runner.8714966150718292736
    -----
    Target //:foo up-to-date:
      bazel-bin/foo
    INFO: Elapsed time: 0.350s, Critical Path: 0.02s
    INFO: 2 processes: 1 internal, 1 local.
    INFO: Build completed successfully, 2 total actions