use of com.google.idea.blaze.base.command.buildresult.BuildResultHelper.GetArtifactsException in project intellij by bazelbuild.
the class BlazeGoRunConfigurationRunner method getExecutableToDebug.
/**
* Builds blaze go target and returns the output build artifact.
*
* @throws ExecutionException if the target cannot be debugged.
*/
private static ExecutableInfo getExecutableToDebug(ExecutionEnvironment env) throws ExecutionException {
BlazeCommandRunConfiguration configuration = BlazeCommandRunConfigurationRunner.getConfiguration(env);
Project project = configuration.getProject();
BlazeProjectData blazeProjectData = BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
if (blazeProjectData == null) {
throw new ExecutionException("Not synced yet, please sync project");
}
Label label = getSingleTarget(configuration);
SaveUtil.saveAllFiles();
// locally
try (BuildResultHelper buildResultHelper = BuildResultHelperProvider.createForLocalBuild(project)) {
ImmutableList.Builder<String> flags = ImmutableList.builder();
if (Blaze.getBuildSystemName(project) == BuildSystemName.Blaze) {
// $ go tool compile
// -N disable optimizations
// -l disable inlining
flags.add("--gc_goopt=-N").add("--gc_goopt=-l");
} else {
// bazel build adds these flags themselves with -c dbg
// https://github.com/bazelbuild/rules_go/issues/741
flags.add("--compilation_mode=dbg");
}
Optional<Path> scriptPath = Optional.empty();
if (scriptPathEnabled.getValue()) {
try {
scriptPath = Optional.of(BlazeBeforeRunCommandHelper.createScriptPathFile());
flags.add("--script_path=" + scriptPath.get());
} catch (IOException e) {
// Could still work without script path.
// Script path is only needed to parse arguments from target.
logger.warn("Failed to create script path file. Target arguments will not be parsed.", e);
}
}
ListenableFuture<BuildResult> buildOperation = BlazeBeforeRunCommandHelper.runBlazeCommand(scriptPath.isPresent() ? BlazeCommandName.RUN : BlazeCommandName.BUILD, configuration, buildResultHelper, flags.build(), ImmutableList.of("--dynamic_mode=off", "--test_sharding_strategy=disabled"), BlazeInvocationContext.runConfigContext(ExecutorType.fromExecutor(env.getExecutor()), configuration.getType(), true), "Building debug binary");
try {
BuildResult result = buildOperation.get();
if (result.outOfMemory()) {
throw new ExecutionException("Out of memory while trying to build debug target");
} else if (result.status == Status.BUILD_ERROR) {
throw new ExecutionException("Build error while trying to build debug target");
} else if (result.status == Status.FATAL_ERROR) {
throw new ExecutionException(String.format("Fatal error (%d) while trying to build debug target", result.exitCode));
}
} catch (InterruptedException | CancellationException e) {
buildOperation.cancel(true);
throw new RunCanceledByUserException();
} catch (java.util.concurrent.ExecutionException e) {
throw new ExecutionException(e);
}
if (scriptPath.isPresent()) {
if (!Files.exists(scriptPath.get())) {
throw new ExecutionException(String.format("No debugger executable script path file produced. Expected file at: %s", scriptPath.get()));
}
WorkspaceRoot workspaceRoot = WorkspaceRoot.fromProject(project);
BlazeInfo blazeInfo = BlazeProjectDataManager.getInstance(project).getBlazeProjectData().getBlazeInfo();
return parseScriptPathFile(workspaceRoot, blazeInfo.getExecutionRoot(), scriptPath.get());
} else {
List<File> candidateFiles;
try {
candidateFiles = BlazeArtifact.getLocalFiles(buildResultHelper.getBuildArtifactsForTarget(label, file -> true)).stream().filter(File::canExecute).collect(Collectors.toList());
} catch (GetArtifactsException e) {
throw new ExecutionException(String.format("Failed to get output artifacts when building %s: %s", label, e.getMessage()));
}
if (candidateFiles.isEmpty()) {
throw new ExecutionException(String.format("No output artifacts found when building %s", label));
}
File binary = findExecutable(label, candidateFiles);
if (binary == null) {
throw new ExecutionException(String.format("More than 1 executable was produced when building %s; " + "don't know which one to debug", label));
}
LocalFileSystem.getInstance().refreshIoFiles(ImmutableList.of(binary));
File workingDir = getWorkingDirectory(WorkspaceRoot.fromProject(project), binary);
return new ExecutableInfo(binary, workingDir, ImmutableList.of(), ImmutableMap.of());
}
}
}
use of com.google.idea.blaze.base.command.buildresult.BuildResultHelper.GetArtifactsException in project intellij by bazelbuild.
the class ClassFileManifestBuilder method buildManifest.
/**
* Builds a .class file manifest, then diffs against any previously calculated manifest for this
* debugging session.
*
* @return null if no diff is available (either no manifest could be calculated, or no previously
* calculated manifest is available.
*/
@Nullable
public static ClassFileManifest.Diff buildManifest(ExecutionEnvironment env, @Nullable HotSwapProgress progress) throws ExecutionException {
if (!HotSwapUtils.canHotSwap(env)) {
return null;
}
BlazeCommandRunConfiguration configuration = BlazeCommandRunConfigurationRunner.getConfiguration(env);
Project project = configuration.getProject();
BlazeProjectData projectData = BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
if (projectData == null) {
throw new ExecutionException("Not synced yet; please sync project");
}
JavaClasspathAspectStrategy aspectStrategy = JavaClasspathAspectStrategy.findStrategy(projectData.getBlazeVersionData());
if (aspectStrategy == null) {
return null;
}
SaveUtil.saveAllFiles();
// locally
try (BuildResultHelper buildResultHelper = BuildResultHelperProvider.createForLocalBuild(project)) {
ListenableFuture<BuildResult> buildOperation = BlazeBeforeRunCommandHelper.runBlazeCommand(BlazeCommandName.BUILD, configuration, buildResultHelper, aspectStrategy.getBuildFlags(), ImmutableList.of(), BlazeInvocationContext.runConfigContext(ExecutorType.fromExecutor(env.getExecutor()), configuration.getType(), true), "Building debug binary");
if (progress != null) {
progress.setCancelWorker(() -> buildOperation.cancel(true));
}
try {
BuildResult result = buildOperation.get();
if (result.status != BuildResult.Status.SUCCESS) {
throw new ExecutionException("Blaze failure building debug binary");
}
} catch (InterruptedException | CancellationException e) {
buildOperation.cancel(true);
throw new RunCanceledByUserException();
} catch (java.util.concurrent.ExecutionException e) {
throw new ExecutionException(e);
}
ImmutableList<File> jars;
try {
jars = BlazeArtifact.getLocalFiles(buildResultHelper.getArtifactsForOutputGroup(JavaClasspathAspectStrategy.OUTPUT_GROUP, file -> true)).stream().filter(f -> f.getName().endsWith(".jar")).collect(toImmutableList());
} catch (GetArtifactsException e) {
throw new ExecutionException("Failed to get debug binary: " + e.getMessage());
}
ClassFileManifest oldManifest = getManifest(env);
ClassFileManifest newManifest = ClassFileManifest.build(jars, oldManifest);
env.getCopyableUserData(MANIFEST_KEY).set(newManifest);
return oldManifest != null ? ClassFileManifest.modifiedClasses(oldManifest, newManifest) : null;
}
}
use of com.google.idea.blaze.base.command.buildresult.BuildResultHelper.GetArtifactsException in project intellij by bazelbuild.
the class BuildPluginBeforeRunTaskProvider method executeTask.
@Override
public final boolean executeTask(final DataContext dataContext, final RunConfiguration configuration, final ExecutionEnvironment env, Task task) {
if (!canExecuteTask(configuration, task)) {
return false;
}
BlazeUserSettings userSettings = BlazeUserSettings.getInstance();
return Scope.root(context -> {
WorkspaceRoot workspaceRoot = WorkspaceRoot.fromProject(project);
context.push(new ExperimentScope()).push(new ProblemsViewScope(project, userSettings.getShowProblemsViewOnRun())).push(new BlazeConsoleScope.Builder(project).setPopupBehavior(userSettings.getShowBlazeConsoleOnRun()).addConsoleFilters(new IssueOutputFilter(project, workspaceRoot, ContextType.BeforeRunTask, true)).build()).push(new ToolWindowScope.Builder(project, new com.google.idea.blaze.base.toolwindow.Task(project, "Build Plugin Jar", com.google.idea.blaze.base.toolwindow.Task.Type.BEFORE_LAUNCH)).setPopupBehavior(userSettings.getShowBlazeConsoleOnRun()).setIssueParsers(BlazeIssueParser.defaultIssueParsers(project, WorkspaceRoot.fromProject(project), ContextType.BeforeRunTask)).build()).push(new IdeaLogScope());
BlazeIntellijPluginDeployer deployer = env.getUserData(BlazeIntellijPluginDeployer.USER_DATA_KEY);
if (deployer == null) {
IssueOutput.error("Could not find BlazeIntellijPluginDeployer in env.").submit(context);
return false;
}
deployer.buildStarted();
final ProjectViewSet projectViewSet = ProjectViewManager.getInstance(project).getProjectViewSet();
if (projectViewSet == null) {
IssueOutput.error("Could not load project view. Please resync project").submit(context);
return false;
}
final ScopedTask<Void> buildTask = new ScopedTask<Void>(context) {
@Override
protected Void execute(BlazeContext context) {
String binaryPath = Blaze.getBuildSystemProvider(project).getBinaryPath(project);
BlazeIntellijPluginConfiguration config = (BlazeIntellijPluginConfiguration) configuration;
ListenableFuture<String> executionRootFuture = BlazeInfoRunner.getInstance().runBlazeInfo(context, binaryPath, workspaceRoot, config.getBlazeFlagsState().getFlagsForExternalProcesses(), BlazeInfo.EXECUTION_ROOT_KEY);
String executionRoot;
try {
executionRoot = executionRootFuture.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
context.setCancelled();
return null;
} catch (ExecutionException e) {
IssueOutput.error(e.getMessage()).submit(context);
context.setHasError();
return null;
}
if (executionRoot == null) {
IssueOutput.error("Could not determine execution root").submit(context);
return null;
}
BlazeProjectData blazeProjectData = BlazeProjectDataManager.getInstance(project).getBlazeProjectData();
if (blazeProjectData == null) {
IssueOutput.error("Could not determine execution root").submit(context);
return null;
}
// expects the outputs to be available locally
try (BuildResultHelper buildResultHelper = BuildResultHelperProvider.createForLocalBuild(project)) {
BlazeCommand command = BlazeCommand.builder(binaryPath, BlazeCommandName.BUILD).addTargets(config.getTargets()).addBlazeFlags(BlazeFlags.blazeFlags(project, projectViewSet, BlazeCommandName.BUILD, context, BlazeInvocationContext.runConfigContext(ExecutorType.fromExecutor(env.getExecutor()), config.getType(), true))).addBlazeFlags(config.getBlazeFlagsState().getFlagsForExternalProcesses()).addExeFlags(config.getExeFlagsState().getFlagsForExternalProcesses()).addBlazeFlags(buildResultHelper.getBuildFlags()).build();
if (command == null || context.hasErrors() || context.isCancelled()) {
return null;
}
SaveUtil.saveAllFiles();
int retVal = ExternalTask.builder(workspaceRoot).addBlazeCommand(command).context(context).stderr(LineProcessingOutputStream.of(BlazeConsoleLineProcessorProvider.getAllStderrLineProcessors(context))).build().run();
if (retVal != 0) {
context.setHasError();
}
ListenableFuture<Void> unusedFuture = FileCaches.refresh(project, context, BlazeBuildOutputs.noOutputs(BuildResult.fromExitCode(retVal)));
try {
deployer.reportBuildComplete(new File(executionRoot), buildResultHelper);
} catch (GetArtifactsException e) {
IssueOutput.error("Failed to get build artifacts: " + e.getMessage()).submit(context);
return null;
}
return null;
}
}
};
ListenableFuture<Void> buildFuture = ProgressiveTaskWithProgressIndicator.builder(project, "Executing blaze build for IntelliJ plugin jar").submitTaskWithResult(buildTask);
try {
Futures.getChecked(buildFuture, ExecutionException.class);
} catch (ExecutionException e) {
context.setHasError();
} catch (CancellationException e) {
context.setCancelled();
}
if (context.hasErrors() || context.isCancelled()) {
return false;
}
return true;
});
}
Aggregations