Search in sources :

Example 1 with NoBuildEvent

use of com.google.devtools.build.lib.analysis.NoBuildEvent in project bazel by bazelbuild.

the class QueryCommand method exec.

/**
   * Exit codes:
   *   0   on successful evaluation.
   *   1   if query evaluation did not complete.
   *   2   if query parsing failed.
   *   3   if errors were reported but evaluation produced a partial result
   *        (only when --keep_going is in effect.)
   */
@Override
public ExitCode exec(CommandEnvironment env, OptionsProvider options) {
    BlazeRuntime runtime = env.getRuntime();
    QueryOptions queryOptions = options.getOptions(QueryOptions.class);
    try {
        env.setupPackageCache(options, runtime.getDefaultsPackageContent());
    } catch (InterruptedException e) {
        env.getReporter().handle(Event.error("query interrupted"));
        return ExitCode.INTERRUPTED;
    } catch (AbruptExitException e) {
        env.getReporter().handle(Event.error(null, "Unknown error: " + e.getMessage()));
        return e.getExitCode();
    }
    String query;
    if (!options.getResidue().isEmpty()) {
        if (!queryOptions.queryFile.isEmpty()) {
            env.getReporter().handle(Event.error("Command-line query and --query_file cannot both be specified"));
            return ExitCode.COMMAND_LINE_ERROR;
        }
        query = Joiner.on(' ').join(options.getResidue());
    } else if (!queryOptions.queryFile.isEmpty()) {
        // Works for absolute or relative query file.
        Path residuePath = env.getWorkingDirectory().getRelative(queryOptions.queryFile);
        try {
            query = new String(FileSystemUtils.readContent(residuePath), StandardCharsets.UTF_8);
        } catch (IOException e) {
            env.getReporter().handle(Event.error("I/O error reading from " + residuePath.getPathString()));
            return ExitCode.COMMAND_LINE_ERROR;
        }
    } else {
        env.getReporter().handle(Event.error(String.format("missing query expression. Type '%s help query' for syntax and help", runtime.getProductName())));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    Iterable<OutputFormatter> formatters = runtime.getQueryOutputFormatters();
    OutputFormatter formatter = OutputFormatter.getFormatter(formatters, queryOptions.outputFormat);
    if (formatter == null) {
        env.getReporter().handle(Event.error(String.format("Invalid output format '%s'. Valid values are: %s", queryOptions.outputFormat, OutputFormatter.formatterNames(formatters))));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    Set<Setting> settings = queryOptions.toSettings();
    boolean streamResults = QueryOutputUtils.shouldStreamResults(queryOptions, formatter);
    QueryEvalResult result;
    AbstractBlazeQueryEnvironment<Target> queryEnv = newQueryEnvironment(env, queryOptions.keepGoing, !streamResults, queryOptions.universeScope, queryOptions.loadingPhaseThreads, settings);
    // 1. Parse and transform query:
    QueryExpression expr;
    try {
        expr = QueryExpression.parse(query, queryEnv);
    } catch (QueryException e) {
        env.getReporter().handle(Event.error(null, "Error while parsing '" + query + "': " + e.getMessage()));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    expr = queryEnv.transformParsedQuery(expr);
    OutputStream out = env.getReporter().getOutErr().getOutputStream();
    ThreadSafeOutputFormatterCallback<Target> callback;
    if (streamResults) {
        disableAnsiCharactersFiltering(env);
        // 2. Evaluate expression:
        StreamedFormatter streamedFormatter = ((StreamedFormatter) formatter);
        streamedFormatter.setOptions(queryOptions, queryOptions.aspectDeps.createResolver(env.getPackageManager(), env.getReporter()));
        callback = streamedFormatter.createStreamCallback(out, queryOptions, queryEnv);
    } else {
        callback = QueryUtil.newOrderedAggregateAllOutputFormatterCallback();
    }
    boolean catastrophe = true;
    try {
        result = queryEnv.evaluateQuery(expr, callback);
        catastrophe = false;
    } catch (QueryException e) {
        catastrophe = false;
        // Keep consistent with reportBuildFileError()
        env.getReporter().handle(Event.error(e.getMessage() == null ? e.toString() : e.getMessage()));
        return ExitCode.ANALYSIS_FAILURE;
    } catch (InterruptedException e) {
        catastrophe = false;
        IOException ioException = callback.getIoException();
        if (ioException == null || ioException instanceof ClosedByInterruptException) {
            env.getReporter().handle(Event.error("query interrupted"));
            return ExitCode.INTERRUPTED;
        } else {
            env.getReporter().handle(Event.error("I/O error: " + e.getMessage()));
            return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
        }
    } catch (IOException e) {
        catastrophe = false;
        env.getReporter().handle(Event.error("I/O error: " + e.getMessage()));
        return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
    } finally {
        if (!catastrophe) {
            try {
                out.flush();
            } catch (IOException e) {
                env.getReporter().handle(Event.error("Failed to flush query results: " + e.getMessage()));
                return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
            }
        }
    }
    env.getEventBus().post(new NoBuildEvent());
    if (!streamResults) {
        disableAnsiCharactersFiltering(env);
        // 3. Output results:
        try {
            Set<Target> targets = ((AggregateAllOutputFormatterCallback<Target>) callback).getResult();
            QueryOutputUtils.output(queryOptions, result, targets, formatter, env.getReporter().getOutErr().getOutputStream(), queryOptions.aspectDeps.createResolver(env.getPackageManager(), env.getReporter()));
        } catch (ClosedByInterruptException | InterruptedException e) {
            env.getReporter().handle(Event.error("query interrupted"));
            return ExitCode.INTERRUPTED;
        } catch (IOException e) {
            env.getReporter().handle(Event.error("I/O error: " + e.getMessage()));
            return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
        } finally {
            try {
                out.flush();
            } catch (IOException e) {
                env.getReporter().handle(Event.error("Failed to flush query results: " + e.getMessage()));
                return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
            }
        }
    }
    if (result.isEmpty()) {
        env.getReporter().handle(Event.info("Empty results"));
    }
    return result.getSuccess() ? ExitCode.SUCCESS : ExitCode.PARTIAL_ANALYSIS_FAILURE;
}
Also used : OutputStream(java.io.OutputStream) QueryEvalResult(com.google.devtools.build.lib.query2.engine.QueryEvalResult) StreamedFormatter(com.google.devtools.build.lib.query2.output.OutputFormatter.StreamedFormatter) AggregateAllOutputFormatterCallback(com.google.devtools.build.lib.query2.engine.QueryUtil.AggregateAllOutputFormatterCallback) QueryOptions(com.google.devtools.build.lib.query2.output.QueryOptions) OutputFormatter(com.google.devtools.build.lib.query2.output.OutputFormatter) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) Target(com.google.devtools.build.lib.packages.Target) QueryExpression(com.google.devtools.build.lib.query2.engine.QueryExpression) Path(com.google.devtools.build.lib.vfs.Path) Setting(com.google.devtools.build.lib.query2.engine.QueryEnvironment.Setting) NoBuildEvent(com.google.devtools.build.lib.analysis.NoBuildEvent) IOException(java.io.IOException) BlazeRuntime(com.google.devtools.build.lib.runtime.BlazeRuntime) QueryException(com.google.devtools.build.lib.query2.engine.QueryException) AbruptExitException(com.google.devtools.build.lib.util.AbruptExitException)

Example 2 with NoBuildEvent

use of com.google.devtools.build.lib.analysis.NoBuildEvent in project bazel by bazelbuild.

the class VersionCommand method exec.

@Override
public ExitCode exec(CommandEnvironment env, OptionsProvider options) {
    BlazeVersionInfo info = BlazeVersionInfo.instance();
    if (info.getSummary() == null) {
        env.getReporter().handle(Event.error("Version information not available"));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    env.getEventBus().post(new NoBuildEvent());
    env.getReporter().getOutErr().printOutLn(info.getSummary());
    return ExitCode.SUCCESS;
}
Also used : BlazeVersionInfo(com.google.devtools.build.lib.analysis.BlazeVersionInfo) NoBuildEvent(com.google.devtools.build.lib.analysis.NoBuildEvent)

Example 3 with NoBuildEvent

use of com.google.devtools.build.lib.analysis.NoBuildEvent 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 4 with NoBuildEvent

use of com.google.devtools.build.lib.analysis.NoBuildEvent in project bazel by bazelbuild.

the class InfoCommand method exec.

@Override
public ExitCode exec(final CommandEnvironment env, final OptionsProvider optionsProvider) {
    final BlazeRuntime runtime = env.getRuntime();
    env.getReporter().switchToAnsiAllowingHandler();
    Options infoOptions = optionsProvider.getOptions(Options.class);
    OutErr outErr = env.getReporter().getOutErr();
    // Creating a BuildConfiguration is expensive and often unnecessary. Delay the creation until
    // it is needed.
    Supplier<BuildConfiguration> configurationSupplier = new Supplier<BuildConfiguration>() {

        private BuildConfiguration configuration;

        @Override
        public BuildConfiguration get() {
            if (configuration != null) {
                return configuration;
            }
            try {
                // In order to be able to answer configuration-specific queries, we need to setup the
                // package path. Since info inherits all the build options, all the necessary information
                // is available here.
                env.setupPackageCache(optionsProvider, runtime.getDefaultsPackageContent(optionsProvider));
                // TODO(bazel-team): What if there are multiple configurations? [multi-config]
                configuration = env.getConfigurations(optionsProvider).getTargetConfigurations().get(0);
                return configuration;
            } catch (InvalidConfigurationException e) {
                env.getReporter().handle(Event.error(e.getMessage()));
                throw new ExitCausingRuntimeException(ExitCode.COMMAND_LINE_ERROR);
            } catch (AbruptExitException e) {
                throw new ExitCausingRuntimeException("unknown error: " + e.getMessage(), e.getExitCode());
            } catch (InterruptedException e) {
                env.getReporter().handle(Event.error("interrupted"));
                throw new ExitCausingRuntimeException(ExitCode.INTERRUPTED);
            }
        }
    };
    Map<String, InfoItem> items = getInfoItemMap(env, optionsProvider);
    try {
        if (infoOptions.showMakeEnvironment) {
            Map<String, String> makeEnv = configurationSupplier.get().getMakeEnvironment();
            for (Map.Entry<String, String> entry : makeEnv.entrySet()) {
                InfoItem item = new InfoItem.MakeInfoItem(entry.getKey(), entry.getValue());
                items.put(item.getName(), item);
            }
        }
        List<String> residue = optionsProvider.getResidue();
        if (residue.size() > 1) {
            env.getReporter().handle(Event.error("at most one key may be specified"));
            return ExitCode.COMMAND_LINE_ERROR;
        }
        String key = residue.size() == 1 ? residue.get(0) : null;
        env.getEventBus().post(new NoBuildEvent());
        if (key != null) {
            // print just the value for the specified key:
            byte[] value;
            if (items.containsKey(key)) {
                value = items.get(key).get(configurationSupplier, env);
            } else {
                env.getReporter().handle(Event.error("unknown key: '" + key + "'"));
                return ExitCode.COMMAND_LINE_ERROR;
            }
            try {
                outErr.getOutputStream().write(value);
                outErr.getOutputStream().flush();
            } catch (IOException e) {
                env.getReporter().handle(Event.error("Cannot write info block: " + e.getMessage()));
                return ExitCode.ANALYSIS_FAILURE;
            }
        } else {
            // print them all
            // We'll need this later anyway
            configurationSupplier.get();
            for (InfoItem infoItem : items.values()) {
                if (infoItem.isHidden()) {
                    continue;
                }
                outErr.getOutputStream().write((infoItem.getName() + ": ").getBytes(StandardCharsets.UTF_8));
                outErr.getOutputStream().write(infoItem.get(configurationSupplier, env));
            }
        }
    } catch (AbruptExitException e) {
        return e.getExitCode();
    } catch (ExitCausingRuntimeException e) {
        return e.getExitCode();
    } catch (IOException e) {
        return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
    } catch (InterruptedException e) {
        return ExitCode.INTERRUPTED;
    }
    return ExitCode.SUCCESS;
}
Also used : OutErr(com.google.devtools.build.lib.util.io.OutErr) NoBuildEvent(com.google.devtools.build.lib.analysis.NoBuildEvent) IOException(java.io.IOException) BlazeRuntime(com.google.devtools.build.lib.runtime.BlazeRuntime) InvalidConfigurationException(com.google.devtools.build.lib.analysis.config.InvalidConfigurationException) BuildConfiguration(com.google.devtools.build.lib.analysis.config.BuildConfiguration) Supplier(com.google.common.base.Supplier) AbruptExitException(com.google.devtools.build.lib.util.AbruptExitException) ImmutableMap(com.google.common.collect.ImmutableMap) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 5 with NoBuildEvent

use of com.google.devtools.build.lib.analysis.NoBuildEvent in project bazel by bazelbuild.

the class CleanCommand method exec.

@Override
public ExitCode exec(CommandEnvironment env, OptionsProvider options) throws ShutdownBlazeServerException {
    Options cleanOptions = options.getOptions(Options.class);
    cleanOptions.expunge_async = cleanOptions.cleanStyle.equals("expunge_async");
    cleanOptions.expunge = cleanOptions.cleanStyle.equals("expunge");
    cleanOptions.async = cleanOptions.cleanStyle.equals("async");
    env.getEventBus().post(new NoBuildEvent());
    if (!cleanOptions.expunge && !cleanOptions.expunge_async && !cleanOptions.async && !cleanOptions.cleanStyle.isEmpty()) {
        env.getReporter().handle(Event.error(null, "Invalid clean_style value '" + cleanOptions.cleanStyle + "'"));
        return ExitCode.COMMAND_LINE_ERROR;
    }
    String asyncName = (cleanOptions.expunge || cleanOptions.expunge_async) ? "--expunge_async" : "--async";
    // for non-Linux platforms (https://github.com/bazelbuild/bazel/issues/1906).
    if ((cleanOptions.expunge_async || cleanOptions.async) && OS.getCurrent() != OS.LINUX) {
        boolean expunge = cleanOptions.expunge_async;
        String fallbackName = expunge ? "--expunge" : "synchronous clean";
        env.getReporter().handle(Event.info(null, /*location*/
        asyncName + " cannot be used on non-Linux platforms, falling back to " + fallbackName));
        cleanOptions.expunge_async = false;
        cleanOptions.expunge = expunge;
        cleanOptions.async = false;
        cleanOptions.cleanStyle = expunge ? "expunge" : "";
    }
    String cleanBanner = (cleanOptions.expunge_async || cleanOptions.async) ? "Starting clean." : "Starting clean (this may take a while). " + "Consider using " + asyncName + " if the clean takes more than several minutes.";
    env.getReporter().handle(Event.info(null, /*location*/
    cleanBanner));
    try {
        String symlinkPrefix = options.getOptions(BuildRequest.BuildRequestOptions.class).getSymlinkPrefix(env.getRuntime().getProductName());
        actuallyClean(env, env.getOutputBase(), cleanOptions, symlinkPrefix);
        return ExitCode.SUCCESS;
    } catch (IOException e) {
        env.getReporter().handle(Event.error(e.getMessage()));
        return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
    } catch (CommandException | ExecException e) {
        env.getReporter().handle(Event.error(e.getMessage()));
        return ExitCode.RUN_FAILURE;
    } catch (InterruptedException e) {
        env.getReporter().handle(Event.error("clean interrupted"));
        return ExitCode.INTERRUPTED;
    }
}
Also used : ExecException(com.google.devtools.build.lib.actions.ExecException) NoBuildEvent(com.google.devtools.build.lib.analysis.NoBuildEvent) IOException(java.io.IOException) CommandException(com.google.devtools.build.lib.shell.CommandException)

Aggregations

NoBuildEvent (com.google.devtools.build.lib.analysis.NoBuildEvent)5 BlazeRuntime (com.google.devtools.build.lib.runtime.BlazeRuntime)3 IOException (java.io.IOException)3 AbruptExitException (com.google.devtools.build.lib.util.AbruptExitException)2 OutErr (com.google.devtools.build.lib.util.io.OutErr)2 Supplier (com.google.common.base.Supplier)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 ExecException (com.google.devtools.build.lib.actions.ExecException)1 BlazeVersionInfo (com.google.devtools.build.lib.analysis.BlazeVersionInfo)1 ConfiguredRuleClassProvider (com.google.devtools.build.lib.analysis.ConfiguredRuleClassProvider)1 BuildConfiguration (com.google.devtools.build.lib.analysis.config.BuildConfiguration)1 InvalidConfigurationException (com.google.devtools.build.lib.analysis.config.InvalidConfigurationException)1 RuleClass (com.google.devtools.build.lib.packages.RuleClass)1 Target (com.google.devtools.build.lib.packages.Target)1 Setting (com.google.devtools.build.lib.query2.engine.QueryEnvironment.Setting)1 QueryEvalResult (com.google.devtools.build.lib.query2.engine.QueryEvalResult)1 QueryException (com.google.devtools.build.lib.query2.engine.QueryException)1 QueryExpression (com.google.devtools.build.lib.query2.engine.QueryExpression)1 AggregateAllOutputFormatterCallback (com.google.devtools.build.lib.query2.engine.QueryUtil.AggregateAllOutputFormatterCallback)1 OutputFormatter (com.google.devtools.build.lib.query2.output.OutputFormatter)1