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;
}
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;
}
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;
}
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;
}
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;
}
}
Aggregations