title: Clean up unreachable generated files in Bazel
body: <p>Suppose I have a very minimal project with an empty <code>WORKSPACE</code> and a single package defined at the project root that simply uses <code>touch</code> to create a file called <code>a</code>, as follows:</p>
  
  <pre><code>genrule(
    name = "target",
    cmd = "touch $@",
    outs = ["a"],
  )
  </code></pre>
  
  <p>If I now run</p>
  
  <pre><code>bazel build //:target
  </code></pre>
  
  <p>the package will be "built" and the <code>a</code> file will be available under <code>bazel-genfiles</code>.</p>
  
  <p>Suppose I now change the <code>BUILD</code> to write the output to a different file, as follows:</p>
  
  <pre><code>genrule(
    name = "target",
    cmd = "touch $@",
    outs = ["b"],
  )
  </code></pre>
  
  <p>Building the same target will result in the file <code>b</code> being available under <code>bazel-genfiles</code>. <code>a</code> will still be there though, even though at this point it's "unreachable" from within the context of the build definition.</p>
  
  <p>Is there a way to ask Bazel to perform some sort of "garbage collection" and remove files (and possibly other content) generated by previous builds that are no longer reachable as-per the current build definition, without getting rid of the entire directory? The <code>bazel clean</code> command seems to adopt the latter behavior.</p>
  
  <p><a href="https://github.com/bazelbuild/bazel/issues/5139" rel="nofollow noreferrer">There seems to be a feature in the works</a>, but apparently it cannot be performed on demand, but rather it executes automatically as soon as a certain threshold has been reached.</p>