Search in sources :

Example 1 with OutErr

use of com.google.devtools.build.lib.util.io.OutErr in project bazel by bazelbuild.

the class BuildResultPrinter method showBuildResult.

/**
   * Shows the result of the build. Information includes the list of up-to-date
   * and failed targets and list of output artifacts for successful targets
   *
   * <p>This corresponds to the --show_result flag.
   */
public void showBuildResult(BuildRequest request, BuildResult result, Collection<ConfiguredTarget> configuredTargets, Collection<AspectValue> aspects) {
    // NOTE: be careful what you print!  We don't want to create a consistency
    // problem where the summary message and the exit code disagree.  The logic
    // here is already complex.
    Collection<ConfiguredTarget> targetsToPrint = filterTargetsToPrint(configuredTargets);
    Collection<AspectValue> aspectsToPrint = filterAspectsToPrint(aspects);
    // Filter the targets we care about into two buckets:
    Collection<ConfiguredTarget> succeeded = new ArrayList<>();
    Collection<ConfiguredTarget> failed = new ArrayList<>();
    for (ConfiguredTarget target : targetsToPrint) {
        Collection<ConfiguredTarget> successfulTargets = result.getSuccessfulTargets();
        (successfulTargets.contains(target) ? succeeded : failed).add(target);
    }
    // Suppress summary if --show_result value is exceeded:
    if (succeeded.size() + failed.size() + aspectsToPrint.size() > request.getBuildOptions().maxResultTargets) {
        return;
    }
    OutErr outErr = request.getOutErr();
    TopLevelArtifactContext context = request.getTopLevelArtifactContext();
    for (ConfiguredTarget target : succeeded) {
        Label label = target.getLabel();
        // For up-to-date targets report generated artifacts, but only
        // if they have associated action and not middleman artifacts.
        boolean headerFlag = true;
        for (Artifact artifact : TopLevelArtifactHelper.getAllArtifactsToBuild(target, context).getImportantArtifacts()) {
            if (shouldPrint(artifact)) {
                if (headerFlag) {
                    outErr.printErr("Target " + label + " up-to-date:\n");
                    headerFlag = false;
                }
                outErr.printErrLn(formatArtifactForShowResults(artifact, request));
            }
        }
        if (headerFlag) {
            outErr.printErr("Target " + label + " up-to-date (nothing to build)\n");
        }
    }
    for (AspectValue aspect : aspectsToPrint) {
        Label label = aspect.getLabel();
        String aspectName = aspect.getConfiguredAspect().getName();
        boolean headerFlag = true;
        NestedSet<Artifact> importantArtifacts = TopLevelArtifactHelper.getAllArtifactsToBuild(aspect, context).getImportantArtifacts();
        for (Artifact importantArtifact : importantArtifacts) {
            if (headerFlag) {
                outErr.printErr("Aspect " + aspectName + " of " + label + " up-to-date:\n");
                headerFlag = false;
            }
            if (shouldPrint(importantArtifact)) {
                outErr.printErrLn(formatArtifactForShowResults(importantArtifact, request));
            }
        }
        if (headerFlag) {
            outErr.printErr("Aspect " + aspectName + " of " + label + " up-to-date (nothing to build)\n");
        }
    }
    for (ConfiguredTarget target : failed) {
        outErr.printErr("Target " + target.getLabel() + " failed to build\n");
        // For failed compilation, it is still useful to examine temp artifacts,
        // (ie, preprocessed and assembler files).
        OutputGroupProvider topLevelProvider = target.getProvider(OutputGroupProvider.class);
        String productName = env.getRuntime().getProductName();
        if (topLevelProvider != null) {
            for (Artifact temp : topLevelProvider.getOutputGroup(OutputGroupProvider.TEMP_FILES)) {
                if (temp.getPath().exists()) {
                    outErr.printErrLn("  See temp at " + OutputDirectoryLinksUtils.getPrettyPath(temp.getPath(), env.getWorkspaceName(), env.getWorkspace(), request.getBuildOptions().getSymlinkPrefix(productName), productName));
                }
            }
        }
    }
    if (!failed.isEmpty() && !request.getOptions(ExecutionOptions.class).verboseFailures) {
        outErr.printErr("Use --verbose_failures to see the command lines of failed build steps.\n");
    }
}
Also used : AspectValue(com.google.devtools.build.lib.skyframe.AspectValue) OutErr(com.google.devtools.build.lib.util.io.OutErr) OutputGroupProvider(com.google.devtools.build.lib.analysis.OutputGroupProvider) ArrayList(java.util.ArrayList) Label(com.google.devtools.build.lib.cmdline.Label) ConfiguredTarget(com.google.devtools.build.lib.analysis.ConfiguredTarget) OutputFileConfiguredTarget(com.google.devtools.build.lib.analysis.OutputFileConfiguredTarget) InputFileConfiguredTarget(com.google.devtools.build.lib.analysis.InputFileConfiguredTarget) Artifact(com.google.devtools.build.lib.actions.Artifact) ExecutionOptions(com.google.devtools.build.lib.exec.ExecutionOptions) TopLevelArtifactContext(com.google.devtools.build.lib.analysis.TopLevelArtifactContext)

Example 2 with OutErr

use of com.google.devtools.build.lib.util.io.OutErr in project bazel by bazelbuild.

the class PrintingEventHandler method setOutErr.

/**
   * Redirect all output to the specified OutErr stream pair.
   * Returns the previous OutErr.
   */
public OutErr setOutErr(OutErr outErr) {
    OutErr prev = this.outErr;
    this.outErr = outErr;
    return prev;
}
Also used : OutErr(com.google.devtools.build.lib.util.io.OutErr)

Example 3 with OutErr

use of com.google.devtools.build.lib.util.io.OutErr in project bazel by bazelbuild.

the class RunCommand method exec.

@Override
public ExitCode exec(CommandEnvironment env, OptionsProvider options) {
    RunOptions runOptions = options.getOptions(RunOptions.class);
    // This list should look like: ["//executable:target", "arg1", "arg2"]
    List<String> targetAndArgs = options.getResidue();
    // The user must at the least specify an executable target.
    if (targetAndArgs.isEmpty()) {
        env.getReporter().handle(Event.error("Must specify a target to run"));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    String targetString = targetAndArgs.get(0);
    List<String> runTargetArgs = targetAndArgs.subList(1, targetAndArgs.size());
    RunUnder runUnder = options.getOptions(BuildConfiguration.Options.class).runUnder;
    OutErr outErr = env.getReporter().getOutErr();
    List<String> targets = (runUnder != null) && (runUnder.getLabel() != null) ? ImmutableList.of(targetString, runUnder.getLabel().toString()) : ImmutableList.of(targetString);
    BuildRequest request = BuildRequest.create(this.getClass().getAnnotation(Command.class).name(), options, env.getRuntime().getStartupOptionsProvider(), targets, outErr, env.getCommandId(), env.getCommandStartTime());
    currentRunUnder = runUnder;
    BuildResult result;
    try {
        result = processRequest(env, request);
    } finally {
        currentRunUnder = null;
    }
    if (!result.getSuccess()) {
        env.getReporter().handle(Event.error("Build failed. Not running target"));
        return result.getExitCondition();
    }
    // Make sure that we have exactly 1 built target (excluding --run_under),
    // and that it is executable.
    // These checks should only fail if keepGoing is true, because we already did
    // validation before the build began.  See {@link #validateTargets()}.
    Collection<ConfiguredTarget> targetsBuilt = result.getSuccessfulTargets();
    ConfiguredTarget targetToRun = null;
    ConfiguredTarget runUnderTarget = null;
    if (targetsBuilt != null) {
        int maxTargets = runUnder != null && runUnder.getLabel() != null ? 2 : 1;
        if (targetsBuilt.size() > maxTargets) {
            env.getReporter().handle(Event.error(SINGLE_TARGET_MESSAGE));
            return ExitCode.COMMAND_LINE_ERROR;
        }
        for (ConfiguredTarget target : targetsBuilt) {
            ExitCode targetValidation = fullyValidateTarget(env, target);
            if (!targetValidation.equals(ExitCode.SUCCESS)) {
                return targetValidation;
            }
            if (runUnder != null && target.getLabel().equals(runUnder.getLabel())) {
                if (runUnderTarget != null) {
                    env.getReporter().handle(Event.error(null, "Can't identify the run_under target from multiple options?"));
                    return ExitCode.COMMAND_LINE_ERROR;
                }
                runUnderTarget = target;
            } else if (targetToRun == null) {
                targetToRun = target;
            } else {
                env.getReporter().handle(Event.error(SINGLE_TARGET_MESSAGE));
                return ExitCode.COMMAND_LINE_ERROR;
            }
        }
    }
    // Handle target & run_under referring to the same target.
    if ((targetToRun == null) && (runUnderTarget != null)) {
        targetToRun = runUnderTarget;
    }
    if (targetToRun == null) {
        env.getReporter().handle(Event.error(NO_TARGET_MESSAGE));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    Path executablePath = Preconditions.checkNotNull(targetToRun.getProvider(FilesToRunProvider.class).getExecutable().getPath());
    BuildConfiguration configuration = targetToRun.getConfiguration();
    if (configuration == null) {
        // The target may be an input file, which doesn't have a configuration. In that case, we
        // choose any target configuration.
        configuration = result.getBuildConfigurationCollection().getTargetConfigurations().get(0);
    }
    Path workingDir;
    try {
        workingDir = ensureRunfilesBuilt(env, targetToRun);
    } catch (CommandException e) {
        env.getReporter().handle(Event.error("Error creating runfiles: " + e.getMessage()));
        return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
    }
    List<String> args = runTargetArgs;
    FilesToRunProvider provider = targetToRun.getProvider(FilesToRunProvider.class);
    RunfilesSupport runfilesSupport = provider == null ? null : provider.getRunfilesSupport();
    if (runfilesSupport != null && runfilesSupport.getArgs() != null) {
        List<String> targetArgs = runfilesSupport.getArgs();
        if (!targetArgs.isEmpty()) {
            args = Lists.newArrayListWithCapacity(targetArgs.size() + runTargetArgs.size());
            args.addAll(targetArgs);
            args.addAll(runTargetArgs);
        }
    }
    String productName = env.getRuntime().getProductName();
    //
    // We now have a unique executable ready to be run.
    //
    // We build up two different versions of the command to run: one with an absolute path, which
    // we'll actually run, and a prettier one with the long absolute path to the executable
    // replaced with a shorter relative path that uses the symlinks in the workspace.
    PathFragment prettyExecutablePath = OutputDirectoryLinksUtils.getPrettyPath(executablePath, env.getWorkspaceName(), env.getWorkspace(), options.getOptions(BuildRequestOptions.class).getSymlinkPrefix(productName), productName);
    List<String> cmdLine = new ArrayList<>();
    if (runOptions.scriptPath == null) {
        PathFragment processWrapperPath = env.getBlazeWorkspace().getBinTools().getExecPath(PROCESS_WRAPPER);
        Preconditions.checkNotNull(processWrapperPath, PROCESS_WRAPPER + " not found in embedded tools");
        cmdLine.add(env.getExecRoot().getRelative(processWrapperPath).getPathString());
        cmdLine.add("-1");
        cmdLine.add("15");
        cmdLine.add("-");
        cmdLine.add("-");
    }
    List<String> prettyCmdLine = new ArrayList<>();
    // at the start of the command line.
    if (runUnder != null) {
        String runUnderValue = runUnder.getValue();
        if (runUnderTarget != null) {
            // --run_under specifies a target. Get the corresponding executable.
            // This must be an absolute path, because the run_under target is only
            // in the runfiles of test targets.
            runUnderValue = runUnderTarget.getProvider(FilesToRunProvider.class).getExecutable().getPath().getPathString();
            // If the run_under command contains any options, make sure to add them
            // to the command line as well.
            List<String> opts = runUnder.getOptions();
            if (!opts.isEmpty()) {
                runUnderValue += " " + ShellEscaper.escapeJoinAll(opts);
            }
        }
        cmdLine.add(configuration.getShellExecutable().getPathString());
        cmdLine.add("-c");
        cmdLine.add(runUnderValue + " " + executablePath.getPathString() + " " + ShellEscaper.escapeJoinAll(args));
        prettyCmdLine.add(configuration.getShellExecutable().getPathString());
        prettyCmdLine.add("-c");
        prettyCmdLine.add(runUnderValue + " " + prettyExecutablePath.getPathString() + " " + ShellEscaper.escapeJoinAll(args));
    } else {
        cmdLine.add(executablePath.getPathString());
        cmdLine.addAll(args);
        prettyCmdLine.add(prettyExecutablePath.getPathString());
        prettyCmdLine.addAll(args);
    }
    // Add a newline between the blaze output and the binary's output.
    outErr.printErrLn("");
    if (runOptions.scriptPath != null) {
        String unisolatedCommand = CommandFailureUtils.describeCommand(CommandDescriptionForm.COMPLETE_UNISOLATED, cmdLine, null, workingDir.getPathString());
        if (writeScript(env, runOptions.scriptPath, unisolatedCommand)) {
            return ExitCode.SUCCESS;
        } else {
            return ExitCode.RUN_FAILURE;
        }
    }
    env.getReporter().handle(Event.info(null, "Running command line: " + ShellEscaper.escapeJoinAll(prettyCmdLine)));
    com.google.devtools.build.lib.shell.Command command = new CommandBuilder().addArgs(cmdLine).setEnv(env.getClientEnv()).setWorkingDir(workingDir).build();
    try {
        // Restore a raw EventHandler if it is registered. This allows for blaze run to produce the
        // actual output of the command being run even if --color=no is specified.
        env.getReporter().switchToAnsiAllowingHandler();
        // The command API is a little strange in that the following statement
        // will return normally only if the program exits with exit code 0.
        // If it ends with any other code, we have to catch BadExitStatusException.
        command.execute(com.google.devtools.build.lib.shell.Command.NO_INPUT, com.google.devtools.build.lib.shell.Command.NO_OBSERVER, outErr.getOutputStream(), outErr.getErrorStream(), true).getTerminationStatus().getExitCode();
        return ExitCode.SUCCESS;
    } catch (BadExitStatusException e) {
        String message = "Non-zero return code '" + e.getResult().getTerminationStatus().getExitCode() + "' from command: " + e.getMessage();
        env.getReporter().handle(Event.error(message));
        return ExitCode.RUN_FAILURE;
    } catch (AbnormalTerminationException e) {
        // The process was likely terminated by a signal in this case.
        return ExitCode.INTERRUPTED;
    } catch (CommandException e) {
        env.getReporter().handle(Event.error("Error running program: " + e.getMessage()));
        return ExitCode.RUN_FAILURE;
    }
}
Also used : BuildRequestOptions(com.google.devtools.build.lib.buildtool.BuildRequest.BuildRequestOptions) RunUnder(com.google.devtools.build.lib.analysis.config.RunUnder) FilesToRunProvider(com.google.devtools.build.lib.analysis.FilesToRunProvider) ExitCode(com.google.devtools.build.lib.util.ExitCode) PathFragment(com.google.devtools.build.lib.vfs.PathFragment) ArrayList(java.util.ArrayList) BuildConfiguration(com.google.devtools.build.lib.analysis.config.BuildConfiguration) RunfilesSupport(com.google.devtools.build.lib.analysis.RunfilesSupport) AbnormalTerminationException(com.google.devtools.build.lib.shell.AbnormalTerminationException) BadExitStatusException(com.google.devtools.build.lib.shell.BadExitStatusException) Path(com.google.devtools.build.lib.vfs.Path) OutErr(com.google.devtools.build.lib.util.io.OutErr) ConfiguredTarget(com.google.devtools.build.lib.analysis.ConfiguredTarget) CommandException(com.google.devtools.build.lib.shell.CommandException) BuildRequest(com.google.devtools.build.lib.buildtool.BuildRequest) BuildResult(com.google.devtools.build.lib.buildtool.BuildResult) CommandBuilder(com.google.devtools.build.lib.util.CommandBuilder)

Example 4 with OutErr

use of com.google.devtools.build.lib.util.io.OutErr in project bazel by bazelbuild.

the class HelpCommand method exec.

@Override
public ExitCode exec(CommandEnvironment env, OptionsProvider options) {
    env.getEventBus().post(new NoBuildEvent());
    BlazeRuntime runtime = env.getRuntime();
    OutErr outErr = env.getReporter().getOutErr();
    Options helpOptions = options.getOptions(Options.class);
    if (options.getResidue().isEmpty()) {
        emitBlazeVersionInfo(outErr, runtime.getProductName());
        emitGenericHelp(outErr, runtime);
        return ExitCode.SUCCESS;
    }
    if (options.getResidue().size() != 1) {
        env.getReporter().handle(Event.error("You must specify exactly one command"));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    String helpSubject = options.getResidue().get(0);
    if (helpSubject.equals("startup_options")) {
        emitBlazeVersionInfo(outErr, runtime.getProductName());
        emitStartupOptions(outErr, helpOptions.helpVerbosity, runtime, getOptionCategories(runtime));
        return ExitCode.SUCCESS;
    } else if (helpSubject.equals("target-syntax")) {
        emitBlazeVersionInfo(outErr, runtime.getProductName());
        emitTargetSyntaxHelp(outErr, getOptionCategories(runtime), runtime.getProductName());
        return ExitCode.SUCCESS;
    } else if (helpSubject.equals("info-keys")) {
        emitInfoKeysHelp(env, outErr);
        return ExitCode.SUCCESS;
    } else if (helpSubject.equals("completion")) {
        emitCompletionHelp(runtime, outErr);
        return ExitCode.SUCCESS;
    } else if (helpSubject.equals("everything-as-html")) {
        new HtmlEmitter(runtime).emit(outErr);
        return ExitCode.SUCCESS;
    }
    BlazeCommand command = runtime.getCommandMap().get(helpSubject);
    if (command == null) {
        ConfiguredRuleClassProvider provider = runtime.getRuleClassProvider();
        RuleClass ruleClass = provider.getRuleClassMap().get(helpSubject);
        if (ruleClass != null && ruleClass.isDocumented()) {
            // There is a rule with a corresponding name
            outErr.printOut(BlazeRuleHelpPrinter.getRuleDoc(helpSubject, provider));
            return ExitCode.SUCCESS;
        } else {
            env.getReporter().handle(Event.error(null, "'" + helpSubject + "' is neither a command nor a build rule"));
            return ExitCode.COMMAND_LINE_ERROR;
        }
    }
    emitBlazeVersionInfo(outErr, runtime.getProductName());
    outErr.printOut(BlazeCommandUtils.getUsage(command.getClass(), getOptionCategories(runtime), helpOptions.helpVerbosity, runtime.getBlazeModules(), runtime.getRuleClassProvider(), runtime.getProductName()));
    return ExitCode.SUCCESS;
}
Also used : OutErr(com.google.devtools.build.lib.util.io.OutErr) BlazeCommand(com.google.devtools.build.lib.runtime.BlazeCommand) ConfiguredRuleClassProvider(com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider) NoBuildEvent(com.google.devtools.build.lib.analysis.NoBuildEvent) RuleClass(com.google.devtools.build.lib.packages.RuleClass) BlazeRuntime(com.google.devtools.build.lib.runtime.BlazeRuntime)

Example 5 with OutErr

use of com.google.devtools.build.lib.util.io.OutErr in project bazel by bazelbuild.

the class BuildResultPrinter method showArtifacts.

/**
   * Prints a flat list of all artifacts built by the passed top-level targets.
   *
   * <p>This corresponds to the --experimental_show_artifacts flag.
   */
public void showArtifacts(BuildRequest request, Collection<ConfiguredTarget> configuredTargets, Collection<AspectValue> aspects) {
    TopLevelArtifactContext context = request.getTopLevelArtifactContext();
    Collection<ConfiguredTarget> targetsToPrint = filterTargetsToPrint(configuredTargets);
    Collection<AspectValue> aspectsToPrint = filterAspectsToPrint(aspects);
    NestedSetBuilder<Artifact> artifactsBuilder = NestedSetBuilder.stableOrder();
    for (ConfiguredTarget target : targetsToPrint) {
        artifactsBuilder.addTransitive(TopLevelArtifactHelper.getAllArtifactsToBuild(target, context).getImportantArtifacts());
    }
    for (AspectValue aspect : aspectsToPrint) {
        artifactsBuilder.addTransitive(TopLevelArtifactHelper.getAllArtifactsToBuild(aspect, context).getImportantArtifacts());
    }
    OutErr outErr = request.getOutErr();
    outErr.printErrLn("Build artifacts:");
    NestedSet<Artifact> artifacts = artifactsBuilder.build();
    for (Artifact artifact : artifacts) {
        if (!artifact.isSourceArtifact()) {
            outErr.printErrLn(">>>" + artifact.getPath());
        }
    }
}
Also used : AspectValue(com.google.devtools.build.lib.skyframe.AspectValue) OutErr(com.google.devtools.build.lib.util.io.OutErr) ConfiguredTarget(com.google.devtools.build.lib.analysis.ConfiguredTarget) OutputFileConfiguredTarget(com.google.devtools.build.lib.analysis.OutputFileConfiguredTarget) InputFileConfiguredTarget(com.google.devtools.build.lib.analysis.InputFileConfiguredTarget) TopLevelArtifactContext(com.google.devtools.build.lib.analysis.TopLevelArtifactContext) Artifact(com.google.devtools.build.lib.actions.Artifact)

Aggregations

OutErr (com.google.devtools.build.lib.util.io.OutErr)10 ConfiguredTarget (com.google.devtools.build.lib.analysis.ConfiguredTarget)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 Artifact (com.google.devtools.build.lib.actions.Artifact)2 InputFileConfiguredTarget (com.google.devtools.build.lib.analysis.InputFileConfiguredTarget)2 NoBuildEvent (com.google.devtools.build.lib.analysis.NoBuildEvent)2 OutputFileConfiguredTarget (com.google.devtools.build.lib.analysis.OutputFileConfiguredTarget)2 TopLevelArtifactContext (com.google.devtools.build.lib.analysis.TopLevelArtifactContext)2 BuildConfiguration (com.google.devtools.build.lib.analysis.config.BuildConfiguration)2 EventHandler (com.google.devtools.build.lib.events.EventHandler)2 BlazeRuntime (com.google.devtools.build.lib.runtime.BlazeRuntime)2 AspectValue (com.google.devtools.build.lib.skyframe.AspectValue)2 AbruptExitException (com.google.devtools.build.lib.util.AbruptExitException)2 ExitCode (com.google.devtools.build.lib.util.ExitCode)2 Path (com.google.devtools.build.lib.vfs.Path)2 Supplier (com.google.common.base.Supplier)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 EnvironmentalExecException (com.google.devtools.build.lib.actions.EnvironmentalExecException)1