com.google.devtools.build.lib.events.Event.error() - java examples

Here are the examples of the java api com.google.devtools.build.lib.events.Event.error() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

112 Examples 7

19 View Complete Implementation : Parser.java
Copyright Apache License 2.0
Author : bazelbuild
private void reportError(Location location, String message) {
    errorsCount++;
    // Limit the number of reported errors to avoid spamming output.
    if (errorsCount <= 5) {
        errors.add(Event.error(location, message));
    }
}

19 View Complete Implementation : BlazeOptionHandler.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * TODO(bazel-team): When we move CoreOptions options to be defined in starlark, make sure they're
 * not preplaceded in here during {@link #getOptionsResult}.
 */
ExitCode parseStarlarkOptions(CommandEnvironment env, ExtendedEventHandler eventHandler) {
    // For now, restrict starlark options to commands that already build to ensure that loading
    // will work. We may want to open this up to other commands in the future. The "info"
    // and "clean" commands have builds=true set in their annotation but don't actually do any
    // building (b/120041419).
    if (!commandAnnotation.builds() || commandAnnotation.name().equals("info") || commandAnnotation.name().equals("clean")) {
        return ExitCode.SUCCESS;
    }
    try {
        StarlarkOptionsParser.newStarlarkOptionsParser(env, optionsParser).parse(eventHandler);
    } catch (OptionsParsingException e) {
        env.getReporter().handle(Event.error(e.getMessage()));
        return ExitCode.PARSING_FAILURE;
    }
    return ExitCode.SUCCESS;
}

19 View Complete Implementation : BuildEventServiceModule.java
Copyright Apache License 2.0
Author : bazelbuild
protected void reportCommandLineError(EventHandler commandLineReporter, Exception exception) {
    // Don't hide unchecked exceptions as part of the error reporting.
    Throwables.throwIfUnchecked(exception);
    commandLineReporter.handle(Event.error(exception.getMessage()));
}

19 View Complete Implementation : TestExpansionFunction.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Populates 'result' with all the tests replacedociated with the specified 'rule'. Throws an exception
 * if any target is missing.
 *
 * <p>CAUTION! Keep this logic consistent with {@code TestSuite}!
 */
private static ResolvedTargets<Label> computeExpandedTests(Environment env, Rule rule, boolean strict) throws InterruptedException {
    Set<Target> result = new HashSet<>();
    boolean hasError = false;
    List<Target> prerequisites = new ArrayList<>();
    // Note that prerequisites can contain input file targets; the test_suite rule does not
    // restrict the set of targets that can appear in tests or suites.
    hasError |= getPrerequisites(env, rule, "tests", prerequisites);
    // 1. Add all tests
    for (Target test : prerequisites) {
        if (TargetUtils.isTestRule(test)) {
            result.add(test);
        } else if (strict && !TargetUtils.isTestSuiteRule(test)) {
            // If strict mode is enabled, then give an error for any non-test, non-test-suite targets.
            // TODO(ulfjack): We need to throw to end the process if we happen to be in --nokeep_going,
            // but we can't know whether or not we are at this point.
            env.getListener().handle(Event.error(rule.getLocation(), "in test_suite rule '" + rule.getLabel() + "': expecting a test or a test_suite rule but '" + test.getLabel() + "' is not one."));
            hasError = true;
        }
    }
    // 2. Add implicit dependencies on tests in same package, if any.
    List<Target> implicitTests = new ArrayList<>();
    hasError |= getPrerequisites(env, rule, "$implicit_tests", implicitTests);
    for (Target target : implicitTests) {
        // The Package construction of $implicit_tests ensures that this check never fails, but we
        // add it here anyway for compatibility with future code.
        if (TargetUtils.isTestRule(target)) {
            result.add(target);
        }
    }
    // 3. Filter based on tags, size, env.
    TestTargetUtils.filterTests(rule, result);
    // 4. Expand all rules recursively, collecting labels.
    ResolvedTargets.Builder<Label> labelsBuilder = ResolvedTargets.builder();
    // Don't set filtered targets; they would be removed from the containing test suite.
    labelsBuilder.merge(new ResolvedTargets<>(toLabels(result), ImmutableSet.of(), hasError));
    for (Target suite : prerequisites) {
        if (TargetUtils.isTestSuiteRule(suite)) {
            TestExpansionValue value = (TestExpansionValue) env.getValue(TestExpansionValue.key(suite, strict));
            if (value == null) {
                continue;
            }
            labelsBuilder.merge(value.getLabels());
        }
    }
    return labelsBuilder.build();
}

19 View Complete Implementation : DumpCommand.java
Copyright Apache License 2.0
Author : bazelbuild
private boolean dumpActionCache(CommandEnvironment env, PrintStream out) {
    try {
        env.getPersistentActionCache().dump(out);
    } catch (IOException e) {
        env.getReporter().handle(Event.error("Cannot dump action cache: " + e.getMessage()));
        return false;
    }
    return true;
}

19 View Complete Implementation : RemoteModule.java
Copyright Apache License 2.0
Author : bazelbuild
private void checkClientServerCompatibility(ServerCapabilities capabilities, RemoteOptions remoteOptions, DigestFunction.Value digestFunction, Reporter reporter) throws AbruptExitException {
    RemoteServerCapabilities.ClientServerCompatibilityStatus st = RemoteServerCapabilities.checkClientServerCompatibility(capabilities, remoteOptions, digestFunction);
    for (String warning : st.getWarnings()) {
        reporter.handle(Event.warn(warning));
    }
    List<String> errors = st.getErrors();
    for (int i = 0; i < errors.size() - 1; ++i) {
        reporter.handle(Event.error(errors.get(i)));
    }
    if (!errors.isEmpty()) {
        throw new AbruptExitException(errors.get(errors.size() - 1), ExitCode.REMOTE_ERROR);
    }
}

19 View Complete Implementation : CppConfiguration.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public void reportInvalidOptions(EventHandler reporter, BuildOptions buildOptions) {
    CppOptions cppOptions = buildOptions.get(CppOptions.clreplaced);
    if (stripBinaries) {
        boolean warn = cppOptions.coptList.contains("-g");
        for (PerLabelOptions opt : cppOptions.perFileCopts) {
            warn |= opt.getOptions().contains("-g");
        }
        if (warn) {
            reporter.handle(Event.warn("Stripping enabled, but '--copt=-g' (or --per_file_copt=...@-g) specified. " + "Debug information will be generated and then stripped away. This is " + "probably not what you want! Use '-c dbg' for debug mode, or use " + "'--strip=never' to disable stripping"));
        }
    }
    // FDO
    if (cppOptions.getFdoOptimize() != null && cppOptions.fdoProfileLabel != null) {
        reporter.handle(Event.error("Both --fdo_optimize and --fdo_profile specified"));
    }
    if (cppOptions.fdoInstrumentForBuild != null) {
        if (cppOptions.getFdoOptimize() != null || cppOptions.fdoProfileLabel != null) {
            reporter.handle(Event.error("Cannot instrument and optimize for FDO at the same time. Remove one of the " + "'--fdo_instrument' and '--fdo_optimize/--fdo_profile' options"));
        }
        if (!cppOptions.coptList.contains("-Wno-error")) {
            // This is effectively impossible. --fdo_instrument adds this value, and only invocation
            // policy could remove it.
            reporter.handle(Event.error("Cannot instrument FDO without --copt including -Wno-error."));
        }
    }
    // This is an replacedertion check vs. user error because users can't trigger this state.
    Verify.verify(!(buildOptions.get(CoreOptions.clreplaced).isHost && cppOptions.isFdo()), "FDO state should not propagate to the host configuration");
}

19 View Complete Implementation : ConfiguredTargetFactory.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns the visibility of the given target. Errors during package group resolution are reported
 * to the {@code replacedysisEnvironment}.
 */
private NestedSet<PackageGroupContents> convertVisibility(OrderedSetMultimap<DependencyKind, ConfiguredTargetAndData> prerequisiteMap, EventHandler reporter, Target target, BuildConfiguration packageGroupConfiguration) {
    RuleVisibility ruleVisibility = target.getVisibility();
    if (ruleVisibility instanceof ConstantRuleVisibility) {
        return ((ConstantRuleVisibility) ruleVisibility).isPubliclyVisible() ? NestedSetBuilder.create(Order.STABLE_ORDER, PackageGroupContents.create(ImmutableList.of(PackageSpecification.everything()))) : NestedSetBuilder.emptySet(Order.STABLE_ORDER);
    } else if (ruleVisibility instanceof PackageGroupsRuleVisibility) {
        PackageGroupsRuleVisibility packageGroupsVisibility = (PackageGroupsRuleVisibility) ruleVisibility;
        NestedSetBuilder<PackageGroupContents> result = NestedSetBuilder.stableOrder();
        for (Label groupLabel : packageGroupsVisibility.getPackageGroups()) {
            // PackageGroupsConfiguredTargets are always in the package-group configuration.
            TransitiveInfoCollection group = findPrerequisite(prerequisiteMap, groupLabel, packageGroupConfiguration);
            PackageSpecificationProvider provider = null;
            // group == null can only happen if the package group list comes
            // from a default_visibility attribute, because in every other case,
            // this missing link is caught during transitive closure visitation or
            // if the RuleConfiguredTargetGraph threw out a visibility edge
            // because if would have caused a cycle. The filtering should be done
            // in a single place, ConfiguredTargetGraph, but for now, this is the
            // minimally invasive way of providing a sane error message in case a
            // cycle is created by a visibility attribute.
            if (group != null) {
                provider = group.getProvider(PackageSpecificationProvider.clreplaced);
            }
            if (provider != null) {
                result.addTransitive(provider.getPackageSpecifications());
            } else {
                reporter.handle(Event.error(target.getLocation(), String.format("Label '%s' does not refer to a package group", groupLabel)));
            }
        }
        result.add(packageGroupsVisibility.getDirectPackages());
        return result.build();
    } else {
        throw new IllegalStateException("unknown visibility");
    }
}

19 View Complete Implementation : BlazeOptionHandler.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Only some commands work if cwd != workspaceSuffix in Blaze. In that case, also check if Blaze
 * was called from the output directory and fail if it was.
 */
private ExitCode checkCwdInWorkspace(EventHandler eventHandler) {
    if (!commandAnnotation.mustRunInWorkspace()) {
        return ExitCode.SUCCESS;
    }
    if (!workspace.getDirectories().inWorkspace()) {
        eventHandler.handle(Event.error("The '" + commandAnnotation.name() + "' command is only supported from within a workspace" + " (below a directory having a WORKSPACE file).\n" + "See doreplacedentation at" + " https://docs.bazel.build/versions/master/build-ref.html#workspace"));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    Path workspacePath = workspace.getWorkspace();
    // TODO(kchodorow): Remove this once spaces are supported.
    if (workspacePath.getPathString().contains(" ")) {
        eventHandler.handle(Event.error(runtime.getProductName() + " does not currently work properly from paths " + "containing spaces (" + workspace + ")."));
        return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
    }
    if (workspacePath.getParentDirectory() != null) {
        Path doNotBuild = workspacePath.getParentDirectory().getRelative(BlazeWorkspace.DO_NOT_BUILD_FILE_NAME);
        if (doNotBuild.exists()) {
            if (!commandAnnotation.canRunInOutputDirectory()) {
                eventHandler.handle(Event.error(getNotInRealWorkspaceError(doNotBuild)));
                return ExitCode.COMMAND_LINE_ERROR;
            } else {
                eventHandler.handle(Event.warn(runtime.getProductName() + " is run from output directory. This is unsound."));
            }
        }
    }
    return ExitCode.SUCCESS;
}

19 View Complete Implementation : BuildConfiguration.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Validates the options for this BuildConfiguration. Issues warnings for the use of deprecated
 * options, and warnings or errors for any option settings that conflict.
 */
public void reportInvalidOptions(EventHandler reporter) {
    for (Fragment fragment : fragments.values()) {
        fragment.reportInvalidOptions(reporter, this.buildOptions);
    }
    if (options.outputDirectoryName != null) {
        reporter.handle(Event.error("The internal '--output directory name' option cannot be used on the command line"));
    }
}

19 View Complete Implementation : SkylarkImportLookupFunction.java
Copyright Apache License 2.0
Author : bazelbuild
// Precondition: file is validated and error-free.
public static void execAndExport(StarlarkFile file, Label extensionLabel, EventHandler handler, StarlarkThread thread) throws InterruptedException {
    // Intercept execution after every replacedignment at top level
    // and "export" any newly replacedigned exportable globals.
    // TODO(adonovan): change the semantics; see b/65374671.
    thread.setPostreplacedignHook((name, value) -> {
        if (value instanceof SkylarkExportable) {
            SkylarkExportable exp = (SkylarkExportable) value;
            if (!exp.isExported()) {
                try {
                    exp.export(extensionLabel, name);
                } catch (EvalException ex) {
                    handler.handle(Event.error(ex.getLocation(), ex.getMessage()));
                }
            }
        }
    });
    try {
        EvalUtils.exec(file, thread);
    } catch (EvalException ex) {
        handler.handle(Event.error(ex.getLocation(), ex.getMessage()));
    }
}

19 View Complete Implementation : RunCommand.java
Copyright Apache License 2.0
Author : bazelbuild
private boolean prepareTestEnvironment(CommandEnvironment env, TestRunnerAction action) {
    try {
        action.prepare(env.getExecRoot());
        return true;
    } catch (IOException e) {
        env.getReporter().handle(Event.error("Error while setting up test: " + e.getMessage()));
        return false;
    }
}

19 View Complete Implementation : EnvironmentGroup.java
Copyright Apache License 2.0
Author : bazelbuild
private boolean isValidEnvironment(Target env, Label envName, String prefix, List<Event> events) {
    if (env == null) {
        events.add(Event.error(location, prefix + "environment " + envName + " does not exist"));
        return false;
    } else if (!env.getTargetKind().equals("environment rule")) {
        events.add(Event.error(location, prefix + env.getLabel() + " is not a valid environment"));
        return false;
    } else if (!environmentLabels.environments.contains(env.getLabel())) {
        events.add(Event.error(location, prefix + env.getLabel() + " is not a member of this group"));
        return false;
    }
    return true;
}

19 View Complete Implementation : Lexer.java
Copyright Apache License 2.0
Author : bazelbuild
private void error(String message, int start, int end) {
    errors.add(Event.error(createLocation(start, end), message));
}

19 View Complete Implementation : EventHandlingErrorReporter.java
Copyright Apache License 2.0
Author : bazelbuild
private void reportError(Location location, String message) {
    // TODO(ulfjack): Consider generating the error message from the root cause event rather than
    // the other way round.
    if (!hasErrors()) {
        // We must not report duplicate events, so we only report the first one for now.
        env.getEventHandler().post(new replacedysisRootCauseEvent(getConfiguration(), getLabel(), message));
    }
    env.getEventHandler().handle(Event.error(location, message));
}

19 View Complete Implementation : SyncCommand.java
Copyright Apache License 2.0
Author : bazelbuild
private static void reportError(CommandEnvironment env, EvaluationResult<SkyValue> value) {
    if (value.getError().getException() != null) {
        env.getReporter().handle(Event.error(value.getError().getException().getMessage()));
    } else {
        env.getReporter().handle(Event.error(value.getError().toString()));
    }
}

19 View Complete Implementation : ConfiguredTargetFactory.java
Copyright Apache License 2.0
Author : bazelbuild
private void validateAdvertisedProviders(ConfiguredAspect configuredAspect, AdvertisedProviderSet advertisedProviders, Target target, EventHandler eventHandler) {
    if (advertisedProviders.canHaveAnyProvider()) {
        return;
    }
    for (Clreplaced<?> aClreplaced : advertisedProviders.getNativeProviders()) {
        if (configuredAspect.getProvider(aClreplaced.replacedubclreplaced(TransitiveInfoProvider.clreplaced)) == null) {
            eventHandler.handle(Event.error(target.getLocation(), String.format("Aspect '%s', applied to '%s', does not provide advertised provider '%s'", configuredAspect.getName(), target.getLabel(), aClreplaced.getSimpleName())));
        }
    }
    for (SkylarkProviderIdentifier providerId : advertisedProviders.getSkylarkProviders()) {
        if (configuredAspect.getProvider(providerId) == null) {
            eventHandler.handle(Event.error(target.getLocation(), String.format("Aspect '%s', applied to '%s', does not provide advertised provider '%s'", configuredAspect.getName(), target.getLabel(), providerId)));
        }
    }
}

19 View Complete Implementation : BuildTool.java
Copyright Apache License 2.0
Author : bazelbuild
private void reportExceptionError(Exception e) {
    if (e.getMessage() != null) {
        getReporter().handle(Event.error(e.getMessage()));
    }
}

19 View Complete Implementation : AspectFunction.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Load Skylark aspect from an extension file. Is to be called from a SkyFunction.
 *
 * @return {@code null} if dependencies cannot be satisfied.
 */
@Nullable
static SkylarkAspect loadSkylarkAspect(Environment env, Label extensionLabel, String skylarkValueName, @Nullable SkylarkImportLookupFunction skylarkImportLookupFunctionForInlining) throws AspectCreationException, InterruptedException {
    SkyKey importFileKey = SkylarkImportLookupValue.key(extensionLabel);
    try {
        SkylarkImportLookupValue skylarkImportLookupValue;
        if (skylarkImportLookupFunctionForInlining == null) {
            // not inlining
            skylarkImportLookupValue = (SkylarkImportLookupValue) env.getValueOrThrow(importFileKey, SkylarkImportFailedException.clreplaced);
        } else {
            skylarkImportLookupValue = skylarkImportLookupFunctionForInlining.computeWithInlineCalls(importFileKey, env, /*visitedDepsInToplevelLoad=*/
            new HashMap<>());
        }
        if (skylarkImportLookupValue == null) {
            Preconditions.checkState(env.valuesMissing(), "no Starlark import value for %s", importFileKey);
            return null;
        }
        Object skylarkValue = skylarkImportLookupValue.getEnvironmentExtension().getBindings().get(skylarkValueName);
        if (skylarkValue == null) {
            throw new ConversionException(String.format("%s is not exported from %s", skylarkValueName, extensionLabel.toString()));
        }
        if (!(skylarkValue instanceof SkylarkAspect)) {
            throw new ConversionException(String.format("%s from %s is not an aspect", skylarkValueName, extensionLabel.toString()));
        }
        return (SkylarkAspect) skylarkValue;
    } catch (SkylarkImportFailedException | ConversionException | InconsistentFilesystemException e) {
        env.getListener().handle(Event.error(e.getMessage()));
        throw new AspectCreationException(e.getMessage(), extensionLabel);
    }
}

18 View Complete Implementation : BuildView.java
Copyright Apache License 2.0
Author : bazelbuild
private static Pair<ImmutableSet<ConfiguredTarget>, ImmutableSet<ConfiguredTarget>> collectTests(TopLevelArtifactContext topLevelOptions, @Nullable Iterable<ConfiguredTarget> allTestTargets, PackageManager packageManager, ExtendedEventHandler eventHandler) throws InterruptedException {
    Set<String> outputGroups = topLevelOptions.outputGroups();
    if (!outputGroups.contains(OutputGroupInfo.FILES_TO_COMPILE) && !outputGroups.contains(OutputGroupInfo.COMPILATION_PREREQUISITES) && allTestTargets != null) {
        final boolean isExclusive = topLevelOptions.runTestsExclusively();
        ImmutableSet.Builder<ConfiguredTarget> targetsToTest = ImmutableSet.builder();
        ImmutableSet.Builder<ConfiguredTarget> targetsToTestExclusive = ImmutableSet.builder();
        for (ConfiguredTarget configuredTarget : allTestTargets) {
            Target target = null;
            try {
                target = packageManager.getTarget(eventHandler, configuredTarget.getLabel());
            } catch (NoSuchTargetException | NoSuchPackageException e) {
                eventHandler.handle(Event.error("Failed to get target when scheduling tests"));
                continue;
            }
            if (target instanceof Rule) {
                if (isExclusive || TargetUtils.isExclusiveTestRule((Rule) target)) {
                    targetsToTestExclusive.add(configuredTarget);
                } else {
                    targetsToTest.add(configuredTarget);
                }
            }
        }
        return Pair.of(targetsToTest.build(), targetsToTestExclusive.build());
    } else {
        return Pair.of(ImmutableSet.of(), ImmutableSet.of());
    }
}

18 View Complete Implementation : BuildTool.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Stops processing the specified request.
 *
 * <p>This logs the build result, cleans up and stops the clock.
 *
 * @param result result to update
 * @param crash any unexpected {@link RuntimeException} or {@link Error}. May be null
 * @param exitCondition a suggested exit condition from either the build logic or a thrown
 *     exception somewhere along the way
 * @param startSuspendCount number of suspensions before the build started
 */
public void stopRequest(BuildResult result, Throwable crash, ExitCode exitCondition, int startSuspendCount) {
    Preconditions.checkState((crash == null) || !exitCondition.equals(ExitCode.SUCCESS));
    int stopSuspendCount = suspendCount();
    Preconditions.checkState(startSuspendCount <= stopSuspendCount);
    result.setUnhandledThrowable(crash);
    result.setExitCondition(exitCondition);
    InterruptedException ie = null;
    try {
        env.getSkyframeExecutor().notifyCommandComplete(env.getReporter());
    } catch (InterruptedException e) {
        env.getReporter().handle(Event.error("Build interrupted during command completion"));
        ie = e;
    }
    // The stop time has to be captured before we send the BuildCompleteEvent.
    result.setStopTime(runtime.getClock().currentTimeMillis());
    result.setWreplaceduspended(stopSuspendCount > startSuspendCount);
    env.getEventBus().post(new BuildPrecompleteEvent());
    env.getEventBus().post(new BuildCompleteEvent(result, ImmutableList.of(BuildEventId.buildToolLogs(), BuildEventId.buildMetrics())));
    // Post the build tool logs event; the corresponding local files may be contributed from
    // modules, and this has to happen after posting the BuildCompleteEvent because that's when
    // modules add their data to the collection.
    env.getEventBus().post(result.getBuildToolLogCollection().freeze().toEvent());
    if (ie != null) {
        if (exitCondition.equals(ExitCode.SUCCESS)) {
            result.setExitCondition(ExitCode.INTERRUPTED);
        } else if (!exitCondition.equals(ExitCode.INTERRUPTED)) {
            logger.log(Level.WARNING, "Suppressed interrupted exception during stop request because already failing with exit" + " code " + exitCondition, ie);
        }
    }
}

18 View Complete Implementation : EnvironmentGroup.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Checks that all environments declared by this group are in the same package as the group (so
 * we can perform an environment --> environment_group lookup and know the package is available)
 * and checks that all defaults are legitimate members of the group.
 *
 * <p>Does <b>not</b> check that the referenced environments exist (see
 * {@link #processMemberEnvironments}).
 *
 * @return a list of validation errors that occurred
 */
List<Event> validateMembership() {
    List<Event> events = new ArrayList<>();
    // All environments should belong to the same package as this group.
    for (Label environment : Iterables.filter(environmentLabels.environments, new DifferentPackage(containingPackage))) {
        events.add(Event.error(location, environment + " is not in the same package as group " + environmentLabels.label));
    }
    // The defaults must be a subset of the member environments.
    for (Label unknownDefault : Sets.difference(environmentLabels.defaults, environmentLabels.environments)) {
        events.add(Event.error(location, "default " + unknownDefault + " is not a " + "declared environment for group " + getLabel()));
    }
    return events;
}

18 View Complete Implementation : Rule.java
Copyright Apache License 2.0
Author : bazelbuild
void reportError(String message, EventHandler eventHandler) {
    eventHandler.handle(Event.error(location, message));
    this.containsErrors = true;
}

18 View Complete Implementation : AbstractBlazeQueryEnvironment.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public void reportBuildFileError(QueryExpression caller, String message) throws QueryException {
    if (!keepGoing) {
        throw new QueryException(caller, message);
    } else {
        // Keep consistent with evaluateQuery() above.
        eventHandler.handle(Event.error("Evaluation of query \"" + caller + "\" failed: " + message));
    }
}

18 View Complete Implementation : RunCommand.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Compute the arguments the binary should be run with by concatenating the arguments in its
 * {@code args=} attribute and the arguments on the Blaze command line.
 */
@Nullable
private List<String> computeArgs(CommandEnvironment env, ConfiguredTarget targetToRun, List<String> commandLineArgs) {
    List<String> args = Lists.newArrayList();
    FilesToRunProvider provider = targetToRun.getProvider(FilesToRunProvider.clreplaced);
    RunfilesSupport runfilesSupport = provider == null ? null : provider.getRunfilesSupport();
    if (runfilesSupport != null && runfilesSupport.getArgs() != null) {
        CommandLine targetArgs = runfilesSupport.getArgs();
        try {
            Iterables.addAll(args, targetArgs.arguments());
        } catch (CommandLineExpansionException e) {
            env.getReporter().handle(Event.error("Could not expand target command line: " + e));
            return null;
        }
    }
    args.addAll(commandLineArgs);
    return args;
}

18 View Complete Implementation : RunCommand.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Performs all available validation checks on an individual target.
 *
 * @param configuredTarget ConfiguredTarget to validate
 * @return BlazeCommandResult.exitCode(ExitCode.SUCCESS) if all checks succeeded, otherwise a
 *     different error code.
 * @throws IllegalStateException if unable to find a target from the package manager.
 */
private ExitCode fullyValidateTarget(CommandEnvironment env, ConfiguredTarget configuredTarget) {
    Target target;
    try {
        target = env.getPackageManager().getTarget(env.getReporter(), configuredTarget.getLabel());
    } catch (NoSuchTargetException | NoSuchPackageException | InterruptedException e) {
        env.getReporter().handle(Event.error("Failed to find a target to validate. " + e));
        throw new IllegalStateException("Failed to find a target to validate");
    }
    String targetError = validateTarget(target);
    if (targetError != null) {
        env.getReporter().handle(Event.error(targetError));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    Artifact executable = configuredTarget.getProvider(FilesToRunProvider.clreplaced).getExecutable();
    if (executable == null) {
        env.getReporter().handle(Event.error(notExecutableError(target)));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    // Shouldn't happen: We just validated the target.
    Preconditions.checkState(executable != null, "Could not find executable for target %s", configuredTarget);
    Path executablePath = executable.getPath();
    try {
        if (!executablePath.exists() || !executablePath.isExecutable()) {
            env.getReporter().handle(Event.error(null, "Non-existent or non-executable " + executablePath));
            return ExitCode.BLAZE_INTERNAL_ERROR;
        }
    } catch (IOException e) {
        env.getReporter().handle(Event.error("Error checking " + executablePath.getPathString() + ": " + e.getMessage()));
        return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
    }
    return ExitCode.SUCCESS;
}

18 View Complete Implementation : ArtifactFunction.java
Copyright Apache License 2.0
Author : bazelbuild
private static void mkdirForTreeArtifact(Artifact artifact, Environment env) throws ArtifactFunctionException {
    try {
        artifact.getPath().createDirectoryAndParents();
    } catch (IOException e) {
        env.getListener().handle(Event.error(String.format("Failed to create output directory for TreeArtifact %s: %s", artifact, e.getMessage())));
        throw new ArtifactFunctionException(e, Transience.TRANSIENT);
    }
}

18 View Complete Implementation : SkyframeLabelVisitor.java
Copyright Apache License 2.0
Author : bazelbuild
private static void errorAboutLoadingFailure(Label topLevelLabel, @Nullable Throwable throwable, ExtendedEventHandler eventHandler) {
    eventHandler.handle(Event.error("Loading of target '" + topLevelLabel + "' failed; build aborted" + (throwable == null ? "" : ": " + throwable.getMessage())));
}

18 View Complete Implementation : ValidationEnvironment.java
Copyright Apache License 2.0
Author : bazelbuild
void addError(Location loc, String message) {
    errors.add(Event.error(loc, message));
}

17 View Complete Implementation : ExecutionTool.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Writes the action cache files to disk, reporting any errors that occurred during writing and
 * capturing statistics.
 */
private void saveActionCache(ActionCache actionCache) {
    ActionCacheStatistics.Builder builder = ActionCacheStatistics.newBuilder();
    actionCache.mergeIntoActionCacheStatistics(builder);
    AutoProfiler p = AutoProfiler.profiledAndLogged("Saving action cache", ProfilerTask.INFO, logger);
    try {
        builder.setSizeInBytes(actionCache.save());
    } catch (IOException e) {
        builder.setSizeInBytes(0);
        getReporter().handle(Event.error("I/O error while writing action log: " + e.getMessage()));
    } finally {
        builder.setSaveTimeInMs(TimeUnit.MILLISECONDS.convert(p.completeAndGetElapsedTimeNanos(), TimeUnit.NANOSECONDS));
    }
    env.getEventBus().post(builder.build());
}

17 View Complete Implementation : TestStrategy.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Outputs test result to the stdout after test has finished (e.g. for --test_output=all or
 * --test_output=errors). Will also try to group output lines together (up to 10000 lines) so
 * parallel test outputs will not get interleaved.
 */
protected void processTestOutput(ActionExecutionContext actionExecutionContext, TestResultData testResultData, String testName, Path testLog) throws IOException {
    boolean isPreplaceded = testResultData.getTestPreplaceded();
    try {
        if (testResultData.getStatus() != BlazeTestStatus.INCOMPLETE && TestLogHelper.shouldOutputTestLog(executionOptions.testOutput, isPreplaceded)) {
            TestLogHelper.writeTestLog(testLog, testName, actionExecutionContext.getFileOutErr().getOutputStream());
        }
    } finally {
        if (isPreplaceded) {
            actionExecutionContext.getEventHandler().handle(Event.of(EventKind.Preplaced, null, testName));
        } else {
            if (testResultData.hreplacedtatusDetails()) {
                actionExecutionContext.getEventHandler().handle(Event.error(testName + ": " + testResultData.getStatusDetails()));
            }
            if (testResultData.getStatus() == BlazeTestStatus.TIMEOUT) {
                actionExecutionContext.getEventHandler().handle(Event.of(EventKind.TIMEOUT, null, testName + " (see " + testLog + ")"));
            } else if (testResultData.getStatus() == BlazeTestStatus.INCOMPLETE) {
                actionExecutionContext.getEventHandler().handle(Event.of(EventKind.CANCELLED, null, testName));
            } else {
                actionExecutionContext.getEventHandler().handle(Event.of(EventKind.FAIL, null, testName + " (see " + testLog + ")"));
            }
        }
    }
}

17 View Complete Implementation : BlazeOptionHandler.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Parses the options, taking care not to generate any output to outErr, return, or throw an
 * exception.
 *
 * @return ExitCode.SUCCESS if everything went well, or some other value if not
 */
ExitCode parseOptions(List<String> args, ExtendedEventHandler eventHandler) {
    // The initialization code here was carefully written to parse the options early before we call
    // into the BlazeModule APIs, which means we must not generate any output to outErr, return, or
    // throw an exception. All the events happening here are instead stored in a temporary event
    // handler, and later replayed.
    ExitCode earlyExitCode = checkCwdInWorkspace(eventHandler);
    if (!earlyExitCode.equals(ExitCode.SUCCESS)) {
        return earlyExitCode;
    }
    try {
        parseArgsAndConfigs(args, eventHandler);
        // Allow the command to edit the options.
        command.editOptions(optionsParser);
        // Migration of --watchfs to a command option.
        // TODO(ulfjack): Get rid of the startup option and drop this code.
        if (runtime.getStartupOptionsProvider().getOptions(BlazeServerStartupOptions.clreplaced).watchFS) {
            try {
                optionsParser.parse("--watchfs");
            } catch (OptionsParsingException e) {
                // This should never happen.
                throw new IllegalStateException(e);
            }
        }
        // Merge the invocation policy that is user-supplied, from the command line, and any
        // invocation policy that was added by a module. The module one goes 'first,' so the user
        // one has priority.
        InvocationPolicy combinedPolicy = InvocationPolicy.newBuilder().mergeFrom(runtime.getModuleInvocationPolicy()).mergeFrom(invocationPolicy).build();
        InvocationPolicyEnforcer optionsPolicyEnforcer = new InvocationPolicyEnforcer(combinedPolicy, Level.INFO);
        // Enforce the invocation policy. It is intentional that this is the last step in preparing
        // the options. The invocation policy is used in security-critical contexts, and may be used
        // as a last resort to override flags. That means that the policy can override flags set in
        // BlazeCommand.editOptions, so the code needs to be safe regardless of the actual flag
        // values. At the time of this writing, editOptions was only used as a convenience feature or
        // to improve the user experience, but not required for safety or correctness.
        optionsPolicyEnforcer.enforce(optionsParser, commandAnnotation.name());
        // Print warnings for odd options usage
        for (String warning : optionsParser.getWarnings()) {
            eventHandler.handle(Event.warn(warning));
        }
        CommonCommandOptions commonOptions = optionsParser.getOptions(CommonCommandOptions.clreplaced);
        for (String warning : commonOptions.deprecationWarnings) {
            eventHandler.handle(Event.warn(warning));
        }
    } catch (OptionsParsingException e) {
        eventHandler.handle(Event.error(e.getMessage()));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    return ExitCode.SUCCESS;
}

17 View Complete Implementation : ProfileCommand.java
Copyright Apache License 2.0
Author : bazelbuild
private static BlazeCommandResult handleOldBinaryProfile(CommandEnvironment env, String dumpMode, PrintStream out, Path profileFile, InfoListener infoListener) {
    try {
        ProfileInfo info = ProfileInfo.loadProfileVerbosely(profileFile, infoListener);
        if (dumpMode != null) {
            dumpProfile(info, out, dumpMode);
            return null;
        }
        ProfileInfo.aggregateProfile(info, infoListener);
        PhaseSummaryStatistics phaseSummaryStatistics = new PhaseSummaryStatistics(info);
        EnumMap<ProfilePhase, PhaseStatistics> phaseStatistics = new EnumMap<>(ProfilePhase.clreplaced);
        for (ProfilePhase phase : ProfilePhase.values()) {
            phaseStatistics.put(phase, new PhaseStatistics(phase, info));
        }
        new PhaseText(out, phaseSummaryStatistics, Optional.of(phaseStatistics), Optional.of(new CriticalPathStatistics(info))).print();
    } catch (IOException e) {
        System.out.println(e);
        env.getReporter().handle(Event.error("Failed to replacedyze profile file(s): " + e.getMessage()));
        return BlazeCommandResult.exitCode(ExitCode.PARSING_FAILURE);
    }
    return null;
}

17 View Complete Implementation : RunCommand.java
Copyright Apache License 2.0
Author : bazelbuild
private boolean writeScript(CommandEnvironment env, PathFragment shellExecutable, PathFragment scriptPathFrag, String cmd) {
    Path scriptPath = env.getWorkingDirectory().getRelative(scriptPathFrag);
    try {
        if (OS.getCurrent() == OS.WINDOWS) {
            FileSystemUtils.writeContent(scriptPath, StandardCharsets.ISO_8859_1, "@echo off\n" + cmd + " %*");
            scriptPath.setExecutable(true);
        } else {
            FileSystemUtils.writeContent(scriptPath, StandardCharsets.ISO_8859_1, "#!" + shellExecutable.getPathString() + "\n" + cmd + " \"$@\"");
            scriptPath.setExecutable(true);
        }
    } catch (IOException e) {
        env.getReporter().handle(Event.error("Error writing run script:" + e.getMessage()));
        return false;
    }
    return true;
}

17 View Complete Implementation : MobileInstallCommand.java
Copyright Apache License 2.0
Author : bazelbuild
private boolean isRuleSupported(CommandEnvironment env, List<String> mobileInstallSupportedRules, String ruleType) {
    if (!mobileInstallSupportedRules.contains(ruleType)) {
        env.getReporter().handle(Event.error(String.format("mobile-install can only be run on %s targets. Got: %s", mobileInstallSupportedRules, ruleType)));
        return false;
    } else {
        return true;
    }
}

17 View Complete Implementation : DockerSandboxedSpawnRunner.java
Copyright Apache License 2.0
Author : bazelbuild
private String getOrCreateCustomizedImage(String baseImage) {
    // TODO(philwo) docker run implicitly does a docker pull if the image does not exist locally.
    // Pulling an image can take a long time and a user might not be aware of that. We could check
    // if the image exists locally (docker images -q name:tag) and if not, do a docker pull and
    // notify the user in a similar way as when we download a http_archive.
    // 
    // This is mostly relevant for the case where we don't build a customized image, as that prints
    // a message when it runs.
    if (!useCustomizedImages) {
        return baseImage;
    }
    // If we're running as root, we can skip this step, as it's safe to replacedume that every image
    // already has a built-in root user and group.
    if (uid == 0 && gid == 0) {
        return baseImage;
    }
    // We only need to create a customized image, if we're running on Linux, as Docker on macOS
    // and Windows doesn't map users from the host into the container anyway.
    if (OS.getCurrent() != OS.LINUX) {
        return baseImage;
    }
    return imageMap.computeIfAbsent(baseImage, (image) -> {
        reporter.handle(Event.info("Preparing Docker image " + image + " for use..."));
        String workDir = PathFragment.create("/execroot").getRelative(execRoot.getBaseName()).getPathString();
        StringBuilder dockerfile = new StringBuilder();
        dockerfile.append(String.format("FROM %s\n", image));
        dockerfile.append(String.format("RUN [\"mkdir\", \"-p\", \"%s\"]\n", workDir));
        // TODO(philwo) this will fail if a user / group with the given uid / gid already exists
        // in the container. For now this seems reasonably unlikely, but we'll have to come up
        // with a better way.
        if (gid > 0) {
            dockerfile.append(String.format("RUN [\"groupadd\", \"-g\", \"%d\", \"bazelbuild\"]\n", gid));
        }
        if (uid > 0) {
            dockerfile.append(String.format("RUN [\"useradd\", \"-m\", \"-g\", \"%d\", \"-d\", \"%s\", \"-N\", \"-u\", " + "\"%d\", \"bazelbuild\"]\n", gid, workDir, uid));
        }
        dockerfile.append(String.format("RUN [\"chown\", \"-R\", \"%d:%d\", \"%s\"]\n", uid, gid, workDir));
        dockerfile.append(String.format("USER %d:%d\n", uid, gid));
        dockerfile.append(String.format("ENV HOME %s\n", workDir));
        if (uid > 0) {
            dockerfile.append(String.format("ENV USER bazelbuild\n"));
        }
        dockerfile.append(String.format("WORKDIR %s\n", workDir));
        try {
            return executeCommand(ImmutableList.of(dockerClient.getPathString(), "build", "-q", "-"), new ByteArrayInputStream(dockerfile.toString().getBytes(Charset.defaultCharset())));
        } catch (UserExecException e) {
            reporter.handle(Event.error(e.getMessage()));
            return null;
        }
    });
}

17 View Complete Implementation : PrepareDepsOfPatternsFunction.java
Copyright Apache License 2.0
Author : bazelbuild
private static void handleTargetParsingException(ExtendedEventHandler eventHandler, String rawPattern, TargetParsingException e) {
    String errorMessage = e.getMessage();
    eventHandler.handle(Event.error("Skipping '" + rawPattern + "': " + errorMessage));
}

17 View Complete Implementation : ProcessPackageDirectory.java
Copyright Apache License 2.0
Author : bazelbuild
private static ProcessPackageDirectoryResult reportErrorAndReturn(String errorPrefix, Exception e, PathFragment rootRelativePath, EventHandler handler) {
    handler.handle(Event.error(errorPrefix + ", for " + rootRelativePath + ", skipping: " + e.getMessage()));
    return ProcessPackageDirectoryResult.EMPTY_RESULT;
}

17 View Complete Implementation : DebugServerTransport.java
Copyright Apache License 2.0
Author : bazelbuild
private void handleParsingError(IOException e) {
    if (isClosed()) {
        // an IOException is expected when the client disconnects -- no need to log an error
        return;
    }
    String message = "Error parsing debug request: " + e.getMessage();
    postEvent(DebugEventHelper.error(message));
    eventHandler.handle(Event.error(message));
}

17 View Complete Implementation : BuildView.java
Copyright Apache License 2.0
Author : bazelbuild
private void addExtraActionsIfRequested(replacedysisOptions viewOptions, Collection<ConfiguredTarget> configuredTargets, Collection<AspectValue> aspects, ArtifactsToOwnerLabels.Builder artifactsToTopLevelLabelsMap, ExtendedEventHandler eventHandler) {
    RegexFilter filter = viewOptions.extraActionFilter;
    for (ConfiguredTarget target : configuredTargets) {
        ExtraActionArtifactsProvider provider = target.getProvider(ExtraActionArtifactsProvider.clreplaced);
        if (provider != null) {
            if (viewOptions.extraActionTopLevelOnly) {
                // Collect all aspect-clreplacedes that topLevel might inject.
                Set<AspectClreplaced> aspectClreplacedes = new HashSet<>();
                Target actualTarget = null;
                try {
                    actualTarget = skyframeExecutor.getPackageManager().getTarget(eventHandler, target.getLabel());
                } catch (NoSuchPackageException | NoSuchTargetException | InterruptedException e) {
                    eventHandler.handle(Event.error(""));
                }
                for (Attribute attr : actualTarget.getreplacedociatedRule().getAttributes()) {
                    aspectClreplacedes.addAll(attr.getAspectClreplacedes());
                }
                TopLevelArtifactHelper.addArtifactsWithOwnerLabel(provider.getExtraActionArtifacts(), filter, target.getLabel(), artifactsToTopLevelLabelsMap);
                if (!aspectClreplacedes.isEmpty()) {
                    TopLevelArtifactHelper.addArtifactsWithOwnerLabel(filterTransitiveExtraActions(provider, aspectClreplacedes), filter, target.getLabel(), artifactsToTopLevelLabelsMap);
                }
            } else {
                TopLevelArtifactHelper.addArtifactsWithOwnerLabel(provider.getTransitiveExtraActionArtifacts(), filter, target.getLabel(), artifactsToTopLevelLabelsMap);
            }
        }
    }
    for (AspectValue aspect : aspects) {
        ExtraActionArtifactsProvider provider = aspect.getConfiguredAspect().getProvider(ExtraActionArtifactsProvider.clreplaced);
        if (provider != null) {
            if (viewOptions.extraActionTopLevelOnly) {
                TopLevelArtifactHelper.addArtifactsWithOwnerLabel(provider.getExtraActionArtifacts(), filter, aspect.getLabel(), artifactsToTopLevelLabelsMap);
            } else {
                TopLevelArtifactHelper.addArtifactsWithOwnerLabel(provider.getTransitiveExtraActionArtifacts(), filter, aspect.getLabel(), artifactsToTopLevelLabelsMap);
            }
        }
    }
}

17 View Complete Implementation : BuildTool.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * The crux of the build system. Builds the targets specified in the request using the specified
 * Executor.
 *
 * <p>Performs loading, replacedysis and execution for the specified set of targets, honoring the
 * configuration options in the BuildRequest. Returns normally iff successful, throws an exception
 * otherwise.
 *
 * <p>The caller is responsible for setting up and syncing the package cache.
 *
 * <p>During this function's execution, the actualTargets and successfulTargets
 * fields of the request object are set.
 *
 * @param request the build request that this build tool is servicing, which specifies various
 *        options; during this method's execution, the actualTargets and successfulTargets fields
 *        of the request object are populated
 * @param validator target validator
 * @return the result as a {@link BuildResult} object
 */
public BuildResult processRequest(BuildRequest request, TargetValidator validator) {
    BuildResult result = new BuildResult(request.getStartTime());
    maybeSetStopOnFirstFailure(request, result);
    int startSuspendCount = suspendCount();
    Throwable catastrophe = null;
    ExitCode exitCode = ExitCode.BLAZE_INTERNAL_ERROR;
    try {
        buildTargets(request, result, validator);
        exitCode = ExitCode.SUCCESS;
    } catch (BuildFailedException e) {
        if (e.isErrorAlreadyShown()) {
        // The actual error has already been reported by the Builder.
        } else {
            reportExceptionError(e);
        }
        if (e.isCatastrophic()) {
            result.setCatastrophe();
        }
        exitCode = e.getExitCode() != null ? e.getExitCode() : ExitCode.BUILD_FAILURE;
    } catch (InterruptedException e) {
        // We may have been interrupted by an error, or the user's interruption may have raced with
        // an error, so check to see if we should report that error code instead.
        exitCode = env.getPendingExitCode();
        if (exitCode == null) {
            exitCode = ExitCode.INTERRUPTED;
            env.getReporter().handle(Event.error("build interrupted"));
            env.getEventBus().post(new BuildInterruptedEvent());
        } else {
            // Report the exception from the environment - the exception we're handling here is just an
            // interruption.
            reportExceptionError(env.getPendingException());
            result.setCatastrophe();
        }
    } catch (TargetParsingException | LoadingFailedException | ViewCreationFailedException e) {
        exitCode = ExitCode.PARSING_FAILURE;
        reportExceptionError(e);
    } catch (PostreplacedysisQueryCommandLineException e) {
        exitCode = ExitCode.COMMAND_LINE_ERROR;
        reportExceptionError(e);
    } catch (TestExecException e) {
        // ExitCode.SUCCESS means that build was successful. Real return code of program
        // is going to be calculated in TestCommand.doTest().
        exitCode = ExitCode.SUCCESS;
        reportExceptionError(e);
    } catch (InvalidConfigurationException e) {
        exitCode = ExitCode.COMMAND_LINE_ERROR;
        reportExceptionError(e);
        // TODO(gregce): With "global configurations" we cannot tie a configuration creation failure
        // to a single target and have to halt the entire build. Once configurations are genuinely
        // created as part of the replacedysis phase they should report their error on the level of the
        // target(s) that triggered them.
        result.setCatastrophe();
    } catch (AbruptExitException e) {
        exitCode = e.getExitCode();
        reportExceptionError(e);
        result.setCatastrophe();
    } catch (Throwable throwable) {
        catastrophe = throwable;
        Throwables.propagate(throwable);
    } finally {
        stopRequest(result, catastrophe, exitCode, startSuspendCount);
    }
    return result;
}

16 View Complete Implementation : ConfigurationResolver.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Checks the config fragments required by a dep against the fragments in its actual
 * configuration. If any are missing, triggers a descriptive "missing fragments" error.
 */
private static void checkForMissingFragments(SkyFunction.Environment env, TargetAndConfiguration ctgValue, Attribute attribute, Dependency dep, Set<Clreplaced<? extends BuildConfiguration.Fragment>> expectedDepFragments) throws ConfiguredTargetFunction.DependencyEvaluationException {
    Set<String> ctgFragmentNames = new HashSet<>();
    for (BuildConfiguration.Fragment fragment : ctgValue.getConfiguration().getFragmentsMap().values()) {
        ctgFragmentNames.add(fragment.getClreplaced().getSimpleName());
    }
    Set<String> depFragmentNames = new HashSet<>();
    for (Clreplaced<? extends BuildConfiguration.Fragment> fragmentClreplaced : expectedDepFragments) {
        depFragmentNames.add(fragmentClreplaced.getSimpleName());
    }
    Set<String> missing = Sets.difference(depFragmentNames, ctgFragmentNames);
    if (!missing.isEmpty()) {
        String msg = String.format("%s: dependency %s from attribute \"%s\" is missing required config fragments: %s", ctgValue.getLabel(), dep.getLabel(), attribute == null ? "(null)" : attribute.getName(), Joiner.on(", ").join(missing));
        env.getListener().handle(Event.error(msg));
        throw new ConfiguredTargetFunction.DependencyEvaluationException(new InvalidConfigurationException(msg));
    }
}

16 View Complete Implementation : SpawnLogModule.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public void executorInit(CommandEnvironment env, BuildRequest request, ExecutorBuilder builder) {
    env.getEventBus().register(this);
    try {
        initOutputs(env);
    } catch (IOException e) {
        env.getReporter().handle(Event.error(e.getMessage()));
        env.getBlazeModuleEnvironment().exit(new AbruptExitException("Error initializing execution log", ExitCode.COMMAND_LINE_ERROR, e));
    }
    if (spawnLogContext != null) {
        // TODO(schmitt): Pretty sure the "spawn-log" commandline identifier is never used as there is
        // no other SpawnLogContext to distinguish from.
        builder.addActionContext(SpawnLogContext.clreplaced, spawnLogContext, "spawn-log");
        builder.addStrategyByContext(SpawnLogContext.clreplaced, "");
    }
}

16 View Complete Implementation : PackageFactory.java
Copyright Apache License 2.0
Author : bazelbuild
@Nullable
private byte[] maybeGetBuildFileBytes(Path buildFile, ExtendedEventHandler eventHandler) {
    try {
        return FileSystemUtils.readWithKnownFileSize(buildFile, buildFile.getFileSize());
    } catch (IOException e) {
        eventHandler.handle(Event.error(Location.fromFile(buildFile.toString()), e.getMessage()));
        return null;
    }
}

16 View Complete Implementation : JavaConfiguration.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public void reportInvalidOptions(EventHandler reporter, BuildOptions buildOptions) {
    if ((bundleTranslations == TriState.YES) && translationTargets.isEmpty()) {
        reporter.handle(Event.error("Translations enabled, but no message translations specified. " + "Use '--message_translations' to select the message translations to use"));
    }
}

16 View Complete Implementation : PythonConfiguration.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public void reportInvalidOptions(EventHandler reporter, BuildOptions buildOptions) {
    PythonOptions opts = buildOptions.get(PythonOptions.clreplaced);
    if (opts.forcePython != null && opts.incompatibleRemoveOldPythonVersionApi) {
        reporter.handle(Event.error("`--force_python` is disabled by `--incompatible_remove_old_python_version_api`"));
    }
    if (opts.incompatiblePy3IsDefault && !opts.incompatibleAllowPythonVersionTransitions) {
        reporter.handle(Event.error("cannot enable `--incompatible_py3_is_default` without also enabling " + "`--incompatible_allow_python_version_transitions`"));
    }
}

16 View Complete Implementation : DumpCommand.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public BlazeCommandResult exec(CommandEnvironment env, OptionsParsingResult options) {
    BlazeRuntime runtime = env.getRuntime();
    DumpOptions dumpOptions = options.getOptions(DumpOptions.clreplaced);
    boolean anyOutput = dumpOptions.dumpPackages || dumpOptions.dumpActionCache || dumpOptions.dumpActionGraph != null || dumpOptions.dumpRuleClreplacedes || dumpOptions.dumpRules || dumpOptions.skylarkMemory != null || (dumpOptions.dumpSkyframe != SkyframeDumpOption.OFF);
    if (!anyOutput) {
        Collection<Clreplaced<? extends OptionsBase>> optionList = new ArrayList<>();
        optionList.add(DumpOptions.clreplaced);
        env.getReporter().getOutErr().printErrLn(BlazeCommandUtils.expandHelpTopic(getClreplaced().getAnnotation(Command.clreplaced).name(), getClreplaced().getAnnotation(Command.clreplaced).help(), getClreplaced(), optionList, OptionsParser.HelpVerbosity.LONG, runtime.getProductName()));
        return BlazeCommandResult.exitCode(ExitCode.replacedYSIS_FAILURE);
    }
    PrintStream out = new PrintStream(env.getReporter().getOutErr().getOutputStream());
    try {
        out.println("Warning: this information is intended for consumption by developers");
        out.println("only, and may change at any time.  Script against it at your own risk!");
        out.println();
        boolean success = true;
        if (dumpOptions.dumpPackages) {
            env.getPackageManager().dump(out);
            out.println();
        }
        if (dumpOptions.dumpActionCache) {
            success &= dumpActionCache(env, out);
            out.println();
        }
        if (dumpOptions.dumpActionGraph != null) {
            try {
                success &= dumpActionGraph(env.getSkyframeExecutor(), dumpOptions.dumpActionGraph, dumpOptions.actionGraphTargets, dumpOptions.actionGraphIncludeCmdLine, dumpOptions.actionGraphIncludeArtifacts, out);
            } catch (CommandLineExpansionException e) {
                env.getReporter().handle(Event.error(null, "Error expanding command line: " + e));
            } catch (IOException e) {
                env.getReporter().error(null, "Could not dump action graph to '" + dumpOptions.dumpActionGraph + "'", e);
            }
        }
        if (dumpOptions.dumpRuleClreplacedes) {
            dumpRuleClreplacedes(runtime, out);
            out.println();
        }
        if (dumpOptions.dumpRules) {
            dumpRuleStats(env.getReporter(), env.getBlazeWorkspace(), env.getSkyframeExecutor(), out);
            out.println();
        }
        if (dumpOptions.skylarkMemory != null) {
            try {
                dumpSkylarkHeap(env.getBlazeWorkspace(), dumpOptions.skylarkMemory, out);
            } catch (IOException e) {
                env.getReporter().error(null, "Could not dump Starlark memory", e);
            }
        }
        if (dumpOptions.dumpSkyframe != SkyframeDumpOption.OFF) {
            success &= dumpSkyframe(env.getSkyframeExecutor(), dumpOptions.dumpSkyframe == SkyframeDumpOption.SUMMARY, out);
            out.println();
        }
        return BlazeCommandResult.exitCode(success ? ExitCode.SUCCESS : ExitCode.replacedYSIS_FAILURE);
    } finally {
        out.flush();
    }
}

16 View Complete Implementation : DockerSandboxedSpawnRunner.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * Returns whether the darwin sandbox is supported on the local machine by running docker info.
 * This is expensive, and we have also reports of docker hanging for a long time!
 */
public static boolean isSupported(CommandEnvironment cmdEnv, Path dockerClient) {
    boolean verbose = cmdEnv.getOptions().getOptions(SandboxOptions.clreplaced).dockerVerbose;
    if (!ProcessWrapperUtil.isSupported(cmdEnv)) {
        if (verbose) {
            cmdEnv.getReporter().handle(Event.error("Docker sandboxing is disabled, because ProcessWrapperUtil.isSupported " + "returned false. This should never happen - is your Bazel binary " + "corrupted?"));
        }
        return false;
    }
    // On Linux we need to know the UID and GID that we're running as, because otherwise Docker will
    // create files as 'root' and we can't move them to the execRoot.
    if (OS.getCurrent() == OS.LINUX) {
        try {
            ProcessUtils.getuid();
            ProcessUtils.getgid();
        } catch (UnsatisfiedLinkError e) {
            if (verbose) {
                cmdEnv.getReporter().handle(Event.error("Docker sandboxing is disabled, because ProcessUtils.getuid/getgid threw an " + "UnsatisfiedLinkError. This means that you're running a Bazel version " + "that doesn't have JNI libraries - did you build it correctly?\n" + Throwables.getStackTracereplacedtring(e)));
            }
            return false;
        }
    }
    Command cmd = new Command(new String[] { dockerClient.getPathString(), "info" }, cmdEnv.getClientEnv(), cmdEnv.getExecRoot().getPathFile());
    try {
        cmd.execute(ByteStreams.nullOutputStream(), ByteStreams.nullOutputStream());
    } catch (CommandException e) {
        if (verbose) {
            cmdEnv.getReporter().handle(Event.error("Docker sandboxing is disabled, because running 'docker info' failed: " + Throwables.getStackTracereplacedtring(e)));
        }
        return false;
    }
    if (verbose) {
        cmdEnv.getReporter().handle(Event.info("Docker sandboxing is supported"));
    }
    return true;
}

16 View Complete Implementation : EnvironmentBackedRecursivePackageProvider.java
Copyright Apache License 2.0
Author : bazelbuild
@Override
public boolean isPackage(ExtendedEventHandler eventHandler, PackageIdentifier packageId) throws MissingDepException, InterruptedException {
    SkyKey packageLookupKey = PackageLookupValue.key(packageId);
    try {
        PackageLookupValue packageLookupValue = (PackageLookupValue) env.getValueOrThrow(packageLookupKey, NoSuchPackageException.clreplaced, InconsistentFilesystemException.clreplaced);
        if (packageLookupValue == null) {
            throw new MissingDepException();
        }
        return packageLookupValue.packageExists();
    } catch (NoSuchPackageException | InconsistentFilesystemException e) {
        env.getListener().handle(Event.error(e.getMessage()));
        encounteredPackageErrors.set(true);
        return false;
    }
}

16 View Complete Implementation : SkyframeBuildView.java
Copyright Apache License 2.0
Author : bazelbuild
/**
 * replacedyzes the specified targets using Skyframe as the driving framework.
 *
 * @return the configured targets that should be built along with a WalkableGraph of the replacedysis.
 */
public SkyframereplacedysisResult configureTargets(ExtendedEventHandler eventHandler, List<ConfiguredTargetKey> ctKeys, List<AspectValueKey> aspectKeys, Supplier<Map<BuildConfigurationValue.Key, BuildConfiguration>> configurationLookupSupplier, EventBus eventBus, boolean keepGoing, int numThreads) throws InterruptedException, ViewCreationFailedException {
    enablereplacedysis(true);
    EvaluationResult<ActionLookupValue> result;
    try (SilentCloseable c = Profiler.instance().profile("skyframeExecutor.configureTargets")) {
        result = skyframeExecutor.configureTargets(eventHandler, ctKeys, aspectKeys, keepGoing, numThreads);
    } finally {
        enablereplacedysis(false);
    }
    Collection<AspectValue> aspects = Lists.newArrayListWithCapacity(aspectKeys.size());
    Root singleSourceRoot = skyframeExecutor.getForcedSingleSourceRootIfNoExecrootSymlinkCreation();
    NestedSetBuilder<Package> packages = singleSourceRoot == null ? NestedSetBuilder.stableOrder() : null;
    for (AspectValueKey aspectKey : aspectKeys) {
        AspectValue value = (AspectValue) result.get(aspectKey);
        if (value == null) {
            // Skip aspects that couldn't be applied to targets.
            continue;
        }
        aspects.add(value);
        if (packages != null) {
            packages.addTransitive(value.getTransitivePackagesForPackageRootResolution());
        }
    }
    Collection<ConfiguredTarget> cts = Lists.newArrayListWithCapacity(ctKeys.size());
    for (ConfiguredTargetKey value : ctKeys) {
        ConfiguredTargetValue ctValue = (ConfiguredTargetValue) result.get(value);
        if (ctValue == null) {
            continue;
        }
        cts.add(ctValue.getConfiguredTarget());
        if (packages != null) {
            packages.addTransitive(ctValue.getTransitivePackagesForPackageRootResolution());
        }
    }
    PackageRoots packageRoots = singleSourceRoot == null ? new MapAsPackageRoots(collectPackageRoots(packages.build().toList())) : new PackageRootsNoSymlinkCreation(singleSourceRoot);
    try (SilentCloseable c = Profiler.instance().profile("skyframeExecutor.findArtifactConflicts")) {
        ImmutableSet<SkyKey> newKeys = ImmutableSet.<SkyKey>builderWithExpectedSize(ctKeys.size() + aspectKeys.size()).addAll(ctKeys).addAll(aspectKeys).build();
        if (checkForConflicts(newKeys)) {
            largestTopLevelKeySetCheckedForConflicts = newKeys;
            // This operation is somewhat expensive, so we only do it if the graph might have changed in
            // some way -- either we replacedyzed a new target or we invalidated an old one or are building
            // targets together that haven't been built before.
            skyframeActionExecutor.findAndStoreArtifactConflicts(skyframeExecutor.getActionLookupValuesInBuild(ctKeys, aspectKeys));
            someConfiguredTargetEvaluated = false;
        }
    }
    ImmutableMap<ActionreplacedysisMetadata, ConflictException> badActions = skyframeActionExecutor.badActions();
    if (!result.hasError() && badActions.isEmpty()) {
        return new SkyframereplacedysisResult(/*hasLoadingError=*/
        false, /*hasreplacedysisError=*/
        false, ImmutableList.copyOf(cts), result.getWalkableGraph(), ImmutableList.copyOf(aspects), packageRoots);
    }
    Pair<Boolean, ViewCreationFailedException> errors = processErrors(result, configurationLookupSupplier, skyframeExecutor, eventHandler, keepGoing, eventBus);
    Collection<Exception> reportedExceptions = Sets.newHashSet();
    for (Map.Entry<ActionreplacedysisMetadata, ConflictException> bad : badActions.entrySet()) {
        ConflictException ex = bad.getValue();
        try {
            ex.rethrowTyped();
        } catch (ActionConflictException ace) {
            ace.reportTo(eventHandler);
            if (keepGoing) {
                eventHandler.handle(Event.warn("errors encountered while replacedyzing target '" + bad.getKey().getOwner().getLabel() + "': it will not be built"));
            }
        } catch (ArtifactPrefixConflictException apce) {
            if (reportedExceptions.add(apce)) {
                eventHandler.handle(Event.error(apce.getMessage()));
            }
        }
        // TODO(ulfjack): Don't throw here in the nokeep_going case, but report all known issues.
        if (!keepGoing) {
            throw new ViewCreationFailedException(ex.getMessage());
        }
    }
    // This is here for backwards compatibility. The keep_going and nokeep_going code paths were
    // checking action conflicts and replacedysis errors in different orders, so we only throw the
    // replacedysis error here after first throwing action conflicts.
    if (!keepGoing) {
        throw errors.second;
    }
    if (!badActions.isEmpty()) {
        // In order to determine the set of configured targets transitively error free from action
        // conflict issues, we run a post-processing update() that uses the bad action map.
        EvaluationResult<PostConfiguredTargetValue> actionConflictResult;
        enablereplacedysis(true);
        try {
            actionConflictResult = skyframeExecutor.postConfigureTargets(eventHandler, ctKeys, keepGoing, badActions);
        } finally {
            enablereplacedysis(false);
        }
        cts = Lists.newArrayListWithCapacity(ctKeys.size());
        for (ConfiguredTargetKey value : ctKeys) {
            PostConfiguredTargetValue postCt = actionConflictResult.get(PostConfiguredTargetValue.key(value));
            if (postCt != null) {
                cts.add(postCt.getCt());
            }
        }
    }
    return new SkyframereplacedysisResult(errors.first, result.hasError() || !badActions.isEmpty(), ImmutableList.copyOf(cts), result.getWalkableGraph(), ImmutableList.copyOf(aspects), packageRoots);
}