Add option to optionally wipe state at the end of a build.

This will serve as an alternative to --batch, leaving behind a server without state from the previous build.

RELNOTES: Introduces --[no]keep_state_after_build
PiperOrigin-RevId: 182778500
diff --git a/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java b/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java
index 65e5954..7789605 100644
--- a/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java
+++ b/src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java
@@ -33,6 +33,7 @@
 import com.google.devtools.build.lib.analysis.config.ConfigurationFragmentFactory;
 import com.google.devtools.build.lib.analysis.test.CoverageReportActionFactory;
 import com.google.devtools.build.lib.buildeventstream.PathConverter;
+import com.google.devtools.build.lib.buildtool.BuildRequestOptions;
 import com.google.devtools.build.lib.clock.BlazeClock;
 import com.google.devtools.build.lib.clock.Clock;
 import com.google.devtools.build.lib.events.Event;
@@ -424,10 +425,7 @@
     workspace.getSkyframeExecutor().getEventBus().post(new CommandCompleteEvent(exitCode));
   }
 
-  /**
-   * Hook method called by the BlazeCommandDispatcher after the dispatch of each
-   * command.
-   */
+  /** Hook method called by the BlazeCommandDispatcher after the dispatch of each command. */
   @VisibleForTesting
   public void afterCommand(CommandEnvironment env, int exitCode) {
     // Remove any filters that the command might have added to the reporter.
@@ -439,6 +437,15 @@
       module.afterCommand();
     }
 
+    // If the command just completed was or inherits from Build, wipe the dependency graph if
+    // requested. This is sufficient, as this method is always run at the end of commands unless
+    // the server crashes, in which case no inmemory state will linger for the next build anyway.
+    BuildRequestOptions buildRequestOptions =
+        env.getOptions().getOptions(BuildRequestOptions.class);
+    if (buildRequestOptions != null && !buildRequestOptions.keepStateAfterBuild) {
+      workspace.getSkyframeExecutor().resetEvaluator();
+    }
+
     env.getBlazeWorkspace().clearEventBus();
 
     try {