use of com.google.idea.blaze.base.scope.BlazeContext 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;
}
BlazeConsolePopupBehavior consolePopupBehavior = BlazeUserSettings.getInstance().getSuppressConsoleForRunAction() ? BlazeConsolePopupBehavior.NEVER : BlazeConsolePopupBehavior.ALWAYS;
return Scope.root(context -> {
WorkspaceRoot workspaceRoot = WorkspaceRoot.fromProject(project);
context.push(new ExperimentScope()).push(new IssuesScope(project, true)).push(new BlazeConsoleScope.Builder(project).setPopupBehavior(consolePopupBehavior).addConsoleFilters(new IssueOutputFilter(project, workspaceRoot, BlazeInvocationContext.NonSync, true)).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();
BlazeIntellijPluginConfiguration config = (BlazeIntellijPluginConfiguration) configuration;
ListenableFuture<String> executionRootFuture = BlazeInfoRunner.getInstance().runBlazeInfo(context, binaryPath, workspaceRoot, config.getBlazeFlagsState().getExpandedFlags(), 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;
}
try (BuildResultHelper buildResultHelper = BuildResultHelper.forFiles(f -> true)) {
BlazeCommand command = BlazeCommand.builder(binaryPath, BlazeCommandName.BUILD).addTargets(config.getTarget()).addBlazeFlags(BlazeFlags.blazeFlags(project, projectViewSet, BlazeCommandName.BUILD, BlazeInvocationContext.NonSync)).addBlazeFlags(config.getBlazeFlagsState().getExpandedFlags()).addExeFlags(config.getExeFlagsState().getExpandedFlags()).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();
}
FileCaches.refresh(project);
deployer.reportBuildComplete(new File(executionRoot), buildResultHelper);
return null;
}
}
};
ListenableFuture<Void> buildFuture = ProgressiveTaskWithProgressIndicator.builder(project).setTitle("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;
});
}
use of com.google.idea.blaze.base.scope.BlazeContext in project intellij by bazelbuild.
the class BlazeBeforeRunCommandHelper method runBlazeBuild.
/**
* Kicks off the blaze build task, returning a corresponding {@link ListenableFuture}.
*/
public static ListenableFuture<BuildResult> runBlazeBuild(BlazeCommandRunConfiguration configuration, BuildResultHelper buildResultHelper, List<String> requiredExtraBlazeFlags, List<String> overridableExtraBlazeFlags, String progressMessage) {
Project project = configuration.getProject();
BlazeCommandRunConfigurationCommonState handlerState = (BlazeCommandRunConfigurationCommonState) configuration.getHandler().getState();
WorkspaceRoot workspaceRoot = WorkspaceRoot.fromProject(project);
ProjectViewSet projectViewSet = ProjectViewManager.getInstance(project).getProjectViewSet();
String binaryPath = handlerState.getBlazeBinaryState().getBlazeBinary() != null ? handlerState.getBlazeBinaryState().getBlazeBinary() : Blaze.getBuildSystemProvider(project).getBinaryPath();
BlazeConsolePopupBehavior consolePopupBehavior = BlazeUserSettings.getInstance().getSuppressConsoleForRunAction() ? BlazeConsolePopupBehavior.NEVER : BlazeConsolePopupBehavior.ALWAYS;
return ProgressiveTaskWithProgressIndicator.builder(project).submitTaskWithResult(new ScopedTask<BuildResult>() {
@Override
protected BuildResult execute(BlazeContext context) {
context.push(new IssuesScope(project, true)).push(new BlazeConsoleScope.Builder(project).setPopupBehavior(consolePopupBehavior).addConsoleFilters(new IssueOutputFilter(project, workspaceRoot, BlazeInvocationContext.NonSync, true)).build());
context.output(new StatusOutput(progressMessage));
BlazeCommand.Builder command = BlazeCommand.builder(binaryPath, BlazeCommandName.BUILD).addTargets(configuration.getTarget()).addBlazeFlags(overridableExtraBlazeFlags).addBlazeFlags(BlazeFlags.blazeFlags(project, projectViewSet, BlazeCommandName.BUILD, BlazeInvocationContext.NonSync)).addBlazeFlags(handlerState.getBlazeFlagsState().getExpandedFlags()).addBlazeFlags(requiredExtraBlazeFlags).addBlazeFlags(buildResultHelper.getBuildFlags());
int exitCode = ExternalTask.builder(workspaceRoot).addBlazeCommand(command.build()).context(context).stderr(LineProcessingOutputStream.of(BlazeConsoleLineProcessorProvider.getAllStderrLineProcessors(context))).build().run();
return BuildResult.fromExitCode(exitCode);
}
});
}
use of com.google.idea.blaze.base.scope.BlazeContext in project intellij by bazelbuild.
the class BlazeConfigurationResolver method buildBlazeConfigurationData.
private void buildBlazeConfigurationData(BlazeContext parentContext, WorkspaceRoot workspaceRoot, ProjectViewSet projectViewSet, BlazeProjectData blazeProjectData, ImmutableMap<TargetKey, CToolchainIdeInfo> toolchainLookupMap, ImmutableMap<File, VirtualFile> headerRoots, ImmutableMap<CToolchainIdeInfo, BlazeCompilerSettings> compilerSettings, CompilerInfoCache compilerInfoCache, ExecutionRootPathResolver executionRootPathResolver, BlazeConfigurationResolverResult oldConfigurationData, BlazeConfigurationResolverResult.Builder builder) {
// Type specification needed to avoid incorrect type inference during command line build.
Scope.push(parentContext, (ScopedOperation) context -> {
context.push(new TimingScope("Build C configuration map", EventType.Other));
ProjectViewTargetImportFilter filter = new ProjectViewTargetImportFilter(project, workspaceRoot, projectViewSet);
ConcurrentMap<TargetKey, BlazeResolveConfigurationData> targetToData = Maps.newConcurrentMap();
List<ListenableFuture<?>> targetToDataFutures = blazeProjectData.targetMap.targets().stream().filter(target -> target.kind.languageClass == LanguageClass.C).filter(target -> target.kind != Kind.CC_TOOLCHAIN).filter(filter::isSourceTarget).filter(BlazeConfigurationResolver::containsCompiledSources).map(target -> submit(() -> {
BlazeResolveConfigurationData data = createResolveConfiguration(target, toolchainLookupMap, headerRoots, compilerSettings, compilerInfoCache, executionRootPathResolver);
if (data != null) {
targetToData.put(target.key, data);
}
return null;
})).collect(Collectors.toList());
try {
Futures.allAsList(targetToDataFutures).get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
context.setCancelled();
return;
} catch (ExecutionException e) {
IssueOutput.error("Could not build C resolve configurations: " + e).submit(context);
logger.error("Could not build C resolve configurations", e);
return;
}
findEquivalenceClasses(context, project, blazeProjectData.workspacePathResolver, targetToData, oldConfigurationData, builder);
});
}
use of com.google.idea.blaze.base.scope.BlazeContext in project intellij by bazelbuild.
the class JdepsFileReader method loadJdepsFiles.
/**
* Loads any updated jdeps files since the last invocation of this method.
*/
@Nullable
public JdepsMap loadJdepsFiles(Project project, BlazeContext parentContext, ArtifactLocationDecoder artifactLocationDecoder, Iterable<TargetIdeInfo> targetsToLoad, SyncState.Builder syncStateBuilder, @Nullable SyncState previousSyncState) {
JdepsState oldState = previousSyncState != null ? previousSyncState.get(JdepsState.class) : null;
JdepsState jdepsState = Scope.push(parentContext, (context) -> {
context.push(new TimingScope("LoadJdepsFiles", EventType.Other));
return doLoadJdepsFiles(project, context, artifactLocationDecoder, oldState, targetsToLoad);
});
if (jdepsState == null) {
return null;
}
syncStateBuilder.put(JdepsState.class, jdepsState);
return targetKey -> jdepsState.targetToJdeps.get(targetKey);
}
use of com.google.idea.blaze.base.scope.BlazeContext in project intellij by bazelbuild.
the class SourceDirectoryCalculator method calculateJavaSourceDirectories.
/**
* Adds the java source directories.
*/
private void calculateJavaSourceDirectories(BlazeContext context, WorkspaceRoot workspaceRoot, ArtifactLocationDecoder artifactLocationDecoder, WorkspacePath directoryRoot, Collection<SourceArtifact> javaArtifacts, Collection<JavaPackageReader> javaPackageReaders, Collection<BlazeSourceDirectory> result) {
List<SourceRoot> sourceRootsPerFile = Lists.newArrayList();
// Get java sources
List<ListenableFuture<SourceRoot>> sourceRootFutures = Lists.newArrayList();
for (final SourceArtifact sourceArtifact : javaArtifacts) {
ListenableFuture<SourceRoot> future = executorService.submit(() -> sourceRootForJavaSource(context, artifactLocationDecoder, sourceArtifact, javaPackageReaders));
sourceRootFutures.add(future);
}
try {
for (SourceRoot sourceRoot : Futures.allAsList(sourceRootFutures).get()) {
if (sourceRoot != null) {
sourceRootsPerFile.add(sourceRoot);
}
}
} catch (ExecutionException | InterruptedException e) {
logger.error(e);
throw new IllegalStateException("Could not read sources");
}
// Sort source roots into their respective directories
Map<WorkspacePath, Multiset<SourceRoot>> sourceDirectoryToSourceRoots = new HashMap<>();
for (SourceRoot sourceRoot : sourceRootsPerFile) {
sourceDirectoryToSourceRoots.computeIfAbsent(sourceRoot.workspacePath, k -> HashMultiset.create()).add(sourceRoot);
}
// Create a mapping from directory to package prefix
Map<WorkspacePath, SourceRoot> workspacePathToSourceRoot = Maps.newHashMap();
for (WorkspacePath workspacePath : sourceDirectoryToSourceRoots.keySet()) {
Multiset<SourceRoot> sources = sourceDirectoryToSourceRoots.get(workspacePath);
Multiset<String> packages = HashMultiset.create();
for (Multiset.Entry<SourceRoot> entry : sources.entrySet()) {
packages.setCount(entry.getElement().packagePrefix, entry.getCount());
}
final String directoryPackagePrefix;
// Common case -- all source files agree on a single package
if (packages.elementSet().size() == 1) {
directoryPackagePrefix = packages.elementSet().iterator().next();
} else {
String preferredPackagePrefix = PackagePrefixCalculator.packagePrefixOf(workspacePath);
directoryPackagePrefix = pickMostFrequentlyOccurring(packages, preferredPackagePrefix);
}
SourceRoot candidateRoot = new SourceRoot(workspacePath, directoryPackagePrefix);
workspacePathToSourceRoot.put(workspacePath, candidateRoot);
}
// Add content entry base if it doesn't exist
if (!workspacePathToSourceRoot.containsKey(directoryRoot)) {
SourceRoot candidateRoot = new SourceRoot(directoryRoot, PackagePrefixCalculator.packagePrefixOf(directoryRoot));
workspacePathToSourceRoot.put(directoryRoot, candidateRoot);
}
// First, create a graph of the directory structure from root to each source file
Map<WorkspacePath, SourceRootDirectoryNode> sourceRootDirectoryNodeMap = Maps.newHashMap();
SourceRootDirectoryNode rootNode = new SourceRootDirectoryNode(directoryRoot, null);
sourceRootDirectoryNodeMap.put(directoryRoot, rootNode);
for (SourceRoot sourceRoot : workspacePathToSourceRoot.values()) {
final String sourcePathRelativeToDirectoryRoot = sourcePathRelativeToDirectoryRoot(directoryRoot, sourceRoot.workspacePath);
List<String> pathComponents = !Strings.isNullOrEmpty(sourcePathRelativeToDirectoryRoot) ? PATH_SPLITTER.splitToList(sourcePathRelativeToDirectoryRoot) : ImmutableList.of();
SourceRootDirectoryNode previousNode = rootNode;
for (int i = 0; i < pathComponents.size(); ++i) {
final WorkspacePath workspacePath = getWorkspacePathFromPathComponents(directoryRoot, pathComponents, i + 1);
SourceRootDirectoryNode node = sourceRootDirectoryNodeMap.get(workspacePath);
if (node == null) {
node = new SourceRootDirectoryNode(workspacePath, pathComponents.get(i));
sourceRootDirectoryNodeMap.put(workspacePath, node);
previousNode.children.add(node);
}
previousNode = node;
}
}
// Add package prefix votes at each directory node
for (SourceRoot sourceRoot : workspacePathToSourceRoot.values()) {
final String sourcePathRelativeToDirectoryRoot = sourcePathRelativeToDirectoryRoot(directoryRoot, sourceRoot.workspacePath);
List<String> packageComponents = PACKAGE_SPLITTER.splitToList(sourceRoot.packagePrefix);
List<String> pathComponents = !Strings.isNullOrEmpty(sourcePathRelativeToDirectoryRoot) ? PATH_SPLITTER.splitToList(sourcePathRelativeToDirectoryRoot) : ImmutableList.of();
int packageIndex = packageComponents.size();
int pathIndex = pathComponents.size();
while (pathIndex >= 0 && packageIndex >= 0) {
final WorkspacePath workspacePath = getWorkspacePathFromPathComponents(directoryRoot, pathComponents, pathIndex);
SourceRootDirectoryNode node = sourceRootDirectoryNodeMap.get(workspacePath);
String packagePrefix = PACKAGE_JOINER.join(packageComponents.subList(0, packageIndex));
// Otherwise just add a vote
if (sourceRoot.workspacePath.equals(workspacePath)) {
node.forcedPackagePrefix = packagePrefix;
} else {
node.packagePrefixVotes.add(packagePrefix);
}
String pathComponent = pathIndex > 0 ? pathComponents.get(pathIndex - 1) : "";
String packageComponent = packageIndex > 0 ? packageComponents.get(packageIndex - 1) : "";
if (!pathComponent.equals(packageComponent)) {
break;
}
--packageIndex;
--pathIndex;
}
}
Map<WorkspacePath, SourceRoot> sourceRoots = Maps.newHashMap();
SourceRootDirectoryNode root = sourceRootDirectoryNodeMap.get(directoryRoot);
visitDirectoryNode(sourceRoots, root, null);
for (SourceRoot sourceRoot : sourceRoots.values()) {
result.add(BlazeSourceDirectory.builder(workspaceRoot.fileForPath(sourceRoot.workspacePath)).setPackagePrefix(sourceRoot.packagePrefix).setGenerated(false).build());
}
}
Aggregations