Search in sources :

Example 1 with BuildManager

use of com.intellij.compiler.server.BuildManager in project intellij-community by JetBrains.

the class GradleResourceCompilerConfigurationGenerator method generateBuildConfiguration.

public void generateBuildConfiguration(@NotNull final CompileContext context) {
    if (shouldBeBuiltByExternalSystem(myProject))
        return;
    if (!hasGradleModules(context))
        return;
    final BuildManager buildManager = BuildManager.getInstance();
    final File projectSystemDir = buildManager.getProjectSystemDirectory(myProject);
    if (projectSystemDir == null)
        return;
    final File gradleConfigFile = new File(projectSystemDir, GradleProjectConfiguration.CONFIGURATION_FILE_RELATIVE_PATH);
    final Map<String, GradleModuleResourceConfiguration> affectedGradleModuleConfigurations = generateAffectedGradleModulesConfiguration(context);
    if (affectedGradleModuleConfigurations.isEmpty())
        return;
    boolean configurationUpdateRequired = context.isRebuild() || !gradleConfigFile.exists();
    final Map<String, Integer> affectedConfigurationHash = new THashMap<>();
    for (Map.Entry<String, GradleModuleResourceConfiguration> entry : affectedGradleModuleConfigurations.entrySet()) {
        Integer moduleLastConfigurationHash = myModulesConfigurationHash.get(entry.getKey());
        int moduleCurrentConfigurationHash = entry.getValue().computeConfigurationHash();
        if (moduleLastConfigurationHash == null || moduleLastConfigurationHash.intValue() != moduleCurrentConfigurationHash) {
            configurationUpdateRequired = true;
        }
        affectedConfigurationHash.put(entry.getKey(), moduleCurrentConfigurationHash);
    }
    final GradleProjectConfiguration projectConfig = loadLastConfiguration(gradleConfigFile);
    // update with newly generated configuration
    projectConfig.moduleConfigurations.putAll(affectedGradleModuleConfigurations);
    final Element element = new Element("gradle-project-configuration");
    XmlSerializer.serializeInto(projectConfig, element);
    final boolean finalConfigurationUpdateRequired = configurationUpdateRequired;
    buildManager.runCommand(() -> {
        if (finalConfigurationUpdateRequired) {
            buildManager.clearState(myProject);
        }
        FileUtil.createIfDoesntExist(gradleConfigFile);
        try {
            JdomKt.write(element, gradleConfigFile.toPath());
            myModulesConfigurationHash.putAll(affectedConfigurationHash);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : Element(org.jdom.Element) IOException(java.io.IOException) THashMap(gnu.trove.THashMap) BuildManager(com.intellij.compiler.server.BuildManager) File(java.io.File) THashMap(gnu.trove.THashMap) Map(java.util.Map) FactoryMap(com.intellij.util.containers.FactoryMap)

Example 2 with BuildManager

use of com.intellij.compiler.server.BuildManager in project intellij-plugins by JetBrains.

the class FlexUnitPrecompileTask method getPathToFlexUnitTempDirectory.

// in case of external build this path is returned by FlexCommonUtils.getPathToFlexUnitTempDirectory()
public static String getPathToFlexUnitTempDirectory(final Project project) {
    final BuildManager buildManager = BuildManager.getInstance();
    final File projectSystemDir = buildManager.getProjectSystemDirectory(project);
    if (projectSystemDir == null) {
        Logger.getInstance(FlexUnitPrecompileTask.class.getName()).error(project);
        return "";
    }
    return FileUtil.toSystemIndependentName(projectSystemDir.getPath()) + "/tmp";
}
Also used : BuildManager(com.intellij.compiler.server.BuildManager) File(java.io.File)

Example 3 with BuildManager

use of com.intellij.compiler.server.BuildManager in project intellij-community by JetBrains.

the class CompileDriver method compileInExternalProcess.

@Nullable
private TaskFuture compileInExternalProcess(@NotNull final CompileContextImpl compileContext, final boolean onlyCheckUpToDate) throws Exception {
    final CompileScope scope = compileContext.getCompileScope();
    final Collection<String> paths = CompileScopeUtil.fetchFiles(compileContext);
    List<TargetTypeBuildScope> scopes = getBuildScopes(compileContext, scope, paths);
    // need to pass scope's user data to server
    final Map<String, String> builderParams;
    if (onlyCheckUpToDate) {
        builderParams = Collections.emptyMap();
    } else {
        final Map<Key, Object> exported = scope.exportUserData();
        if (!exported.isEmpty()) {
            builderParams = new HashMap<>();
            for (Map.Entry<Key, Object> entry : exported.entrySet()) {
                final String _key = entry.getKey().toString();
                final String _value = entry.getValue().toString();
                builderParams.put(_key, _value);
            }
        } else {
            builderParams = Collections.emptyMap();
        }
    }
    final MessageBus messageBus = myProject.getMessageBus();
    final MultiMap<String, Artifact> outputToArtifact = ArtifactCompilerUtil.containsArtifacts(scopes) ? ArtifactCompilerUtil.createOutputToArtifactMap(myProject) : null;
    final BuildManager buildManager = BuildManager.getInstance();
    buildManager.cancelAutoMakeTasks(myProject);
    return buildManager.scheduleBuild(myProject, compileContext.isRebuild(), compileContext.isMake(), onlyCheckUpToDate, scopes, paths, builderParams, new DefaultMessageHandler(myProject) {

        @Override
        public void sessionTerminated(final UUID sessionId) {
            if (compileContext.shouldUpdateProblemsView()) {
                final ProblemsView view = ProblemsView.SERVICE.getInstance(myProject);
                view.clearProgress();
                view.clearOldMessages(compileContext.getCompileScope(), compileContext.getSessionId());
            }
        }

        @Override
        public void handleFailure(UUID sessionId, CmdlineRemoteProto.Message.Failure failure) {
            compileContext.addMessage(CompilerMessageCategory.ERROR, failure.hasDescription() ? failure.getDescription() : "", null, -1, -1);
            final String trace = failure.hasStacktrace() ? failure.getStacktrace() : null;
            if (trace != null) {
                LOG.info(trace);
            }
            compileContext.putUserData(COMPILE_SERVER_BUILD_STATUS, ExitStatus.ERRORS);
        }

        @Override
        protected void handleCompileMessage(UUID sessionId, CmdlineRemoteProto.Message.BuilderMessage.CompileMessage message) {
            final CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind kind = message.getKind();
            //System.out.println(compilerMessage.getText());
            final String messageText = message.getText();
            if (kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.PROGRESS) {
                final ProgressIndicator indicator = compileContext.getProgressIndicator();
                indicator.setText(messageText);
                if (message.hasDone()) {
                    indicator.setFraction(message.getDone());
                }
            } else {
                final CompilerMessageCategory category = kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.ERROR ? CompilerMessageCategory.ERROR : kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.WARNING ? CompilerMessageCategory.WARNING : CompilerMessageCategory.INFORMATION;
                String sourceFilePath = message.hasSourceFilePath() ? message.getSourceFilePath() : null;
                if (sourceFilePath != null) {
                    sourceFilePath = FileUtil.toSystemIndependentName(sourceFilePath);
                }
                final long line = message.hasLine() ? message.getLine() : -1;
                final long column = message.hasColumn() ? message.getColumn() : -1;
                final String srcUrl = sourceFilePath != null ? VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, sourceFilePath) : null;
                compileContext.addMessage(category, messageText, srcUrl, (int) line, (int) column);
                if (compileContext.shouldUpdateProblemsView() && kind == CmdlineRemoteProto.Message.BuilderMessage.CompileMessage.Kind.JPS_INFO) {
                    // treat JPS_INFO messages in a special way: add them as info messages to the problems view
                    final Project project = compileContext.getProject();
                    ProblemsView.SERVICE.getInstance(project).addMessage(new CompilerMessageImpl(project, category, messageText), compileContext.getSessionId());
                }
            }
        }

        @Override
        protected void handleBuildEvent(UUID sessionId, CmdlineRemoteProto.Message.BuilderMessage.BuildEvent event) {
            final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Type eventType = event.getEventType();
            switch(eventType) {
                case FILES_GENERATED:
                    final List<CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile> generated = event.getGeneratedFilesList();
                    final CompilationStatusListener publisher = !myProject.isDisposed() ? messageBus.syncPublisher(CompilerTopics.COMPILATION_STATUS) : null;
                    Set<String> writtenArtifactOutputPaths = outputToArtifact != null ? new THashSet<>(FileUtil.PATH_HASHING_STRATEGY) : null;
                    for (CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.GeneratedFile generatedFile : generated) {
                        final String root = FileUtil.toSystemIndependentName(generatedFile.getOutputRoot());
                        final String relativePath = FileUtil.toSystemIndependentName(generatedFile.getRelativePath());
                        if (publisher != null) {
                            publisher.fileGenerated(root, relativePath);
                        }
                        if (outputToArtifact != null) {
                            Collection<Artifact> artifacts = outputToArtifact.get(root);
                            if (!artifacts.isEmpty()) {
                                for (Artifact artifact : artifacts) {
                                    ArtifactsCompiler.addChangedArtifact(compileContext, artifact);
                                }
                                writtenArtifactOutputPaths.add(FileUtil.toSystemDependentName(DeploymentUtil.appendToPath(root, relativePath)));
                            }
                        }
                    }
                    if (writtenArtifactOutputPaths != null && !writtenArtifactOutputPaths.isEmpty()) {
                        ArtifactsCompiler.addWrittenPaths(compileContext, writtenArtifactOutputPaths);
                    }
                    break;
                case BUILD_COMPLETED:
                    ExitStatus status = ExitStatus.SUCCESS;
                    if (event.hasCompletionStatus()) {
                        final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.Status completionStatus = event.getCompletionStatus();
                        switch(completionStatus) {
                            case CANCELED:
                                status = ExitStatus.CANCELLED;
                                break;
                            case ERRORS:
                                status = ExitStatus.ERRORS;
                                break;
                            case SUCCESS:
                                status = ExitStatus.SUCCESS;
                                break;
                            case UP_TO_DATE:
                                status = ExitStatus.UP_TO_DATE;
                                break;
                        }
                    }
                    compileContext.putUserDataIfAbsent(COMPILE_SERVER_BUILD_STATUS, status);
                    break;
                case CUSTOM_BUILDER_MESSAGE:
                    if (event.hasCustomBuilderMessage()) {
                        final CmdlineRemoteProto.Message.BuilderMessage.BuildEvent.CustomBuilderMessage message = event.getCustomBuilderMessage();
                        if (GlobalOptions.JPS_SYSTEM_BUILDER_ID.equals(message.getBuilderId()) && GlobalOptions.JPS_UNPROCESSED_FS_CHANGES_MESSAGE_ID.equals(message.getMessageType())) {
                            final String text = message.getMessageText();
                            if (!StringUtil.isEmpty(text)) {
                                compileContext.addMessage(CompilerMessageCategory.INFORMATION, text, null, -1, -1);
                            }
                        }
                    }
                    break;
            }
        }
    });
}
Also used : THashSet(gnu.trove.THashSet) MessageBus(com.intellij.util.messages.MessageBus) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) TargetTypeBuildScope(org.jetbrains.jps.api.CmdlineRemoteProto.Message.ControllerMessage.ParametersMessage.TargetTypeBuildScope) DefaultMessageHandler(com.intellij.compiler.server.DefaultMessageHandler) CmdlineRemoteProto(org.jetbrains.jps.api.CmdlineRemoteProto) Artifact(com.intellij.packaging.artifacts.Artifact) THashSet(gnu.trove.THashSet) Project(com.intellij.openapi.project.Project) MessageType(com.intellij.openapi.ui.MessageType) JavaSourceRootType(org.jetbrains.jps.model.java.JavaSourceRootType) BuildManager(com.intellij.compiler.server.BuildManager) HashMap(com.intellij.util.containers.HashMap) MultiMap(com.intellij.util.containers.MultiMap) Key(com.intellij.openapi.util.Key) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with BuildManager

use of com.intellij.compiler.server.BuildManager in project intellij-community by JetBrains.

the class MavenResourceCompilerConfigurationGenerator method generateBuildConfiguration.

public void generateBuildConfiguration(boolean force) {
    if (!myMavenProjectsManager.isMavenizedProject()) {
        return;
    }
    final BuildManager buildManager = BuildManager.getInstance();
    final File projectSystemDir = buildManager.getProjectSystemDirectory(myProject);
    if (projectSystemDir == null) {
        return;
    }
    final File mavenConfigFile = new File(projectSystemDir, MavenProjectConfiguration.CONFIGURATION_FILE_RELATIVE_PATH);
    ProjectRootManager projectRootManager = ProjectRootManager.getInstance(myProject);
    ProjectFileIndex fileIndex = projectRootManager.getFileIndex();
    final int projectRootModificationCount = (int) projectRootManager.getModificationCount();
    final int mavenConfigCrc = myProjectsTree.getFilterConfigCrc(fileIndex);
    final int crc = mavenConfigCrc + projectRootModificationCount;
    final File crcFile = new File(mavenConfigFile.getParent(), "configuration.crc");
    if (!force) {
        try {
            DataInputStream crcInput = new DataInputStream(new FileInputStream(crcFile));
            try {
                final int lastCrc = crcInput.readInt();
                // Project had not change since last config generation.
                if (lastCrc == crc)
                    return;
                LOG.debug(String.format("project configuration changed: lastCrc = %d, currentCrc = %d, projectRootModificationCount = %d, mavenConfigCrc = %d", lastCrc, crc, projectRootModificationCount, mavenConfigCrc));
            } finally {
                crcInput.close();
            }
        } catch (IOException ignored) {
            LOG.debug("Unable to read or find config file: " + ignored.getMessage());
        }
    }
    MavenProjectConfiguration projectConfig = new MavenProjectConfiguration();
    for (MavenProject mavenProject : myMavenProjectsManager.getProjects()) {
        VirtualFile pomXml = mavenProject.getFile();
        Module module = fileIndex.getModuleForFile(pomXml);
        if (module == null)
            continue;
        if (!Comparing.equal(mavenProject.getDirectoryFile(), fileIndex.getContentRootForFile(pomXml)))
            continue;
        MavenModuleResourceConfiguration resourceConfig = new MavenModuleResourceConfiguration();
        MavenId projectId = mavenProject.getMavenId();
        resourceConfig.id = new MavenIdBean(projectId.getGroupId(), projectId.getArtifactId(), projectId.getVersion());
        MavenId parentId = mavenProject.getParentId();
        if (parentId != null) {
            resourceConfig.parentId = new MavenIdBean(parentId.getGroupId(), parentId.getArtifactId(), parentId.getVersion());
        }
        resourceConfig.directory = FileUtil.toSystemIndependentName(mavenProject.getDirectory());
        resourceConfig.delimitersPattern = MavenFilteredPropertyPsiReferenceProvider.getDelimitersPattern(mavenProject).pattern();
        for (Map.Entry<String, String> entry : mavenProject.getModelMap().entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (value != null) {
                resourceConfig.modelMap.put(key, value);
            }
        }
        addEarModelMapEntries(mavenProject, resourceConfig.modelMap);
        Element pluginConfiguration = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-resources-plugin");
        resourceConfig.outputDirectory = getResourcesPluginGoalOutputDirectory(mavenProject, pluginConfiguration, "resources");
        resourceConfig.testOutputDirectory = getResourcesPluginGoalOutputDirectory(mavenProject, pluginConfiguration, "testResources");
        addResources(resourceConfig.resources, mavenProject.getResources());
        addResources(resourceConfig.testResources, mavenProject.getTestResources());
        addWebResources(module, projectConfig, mavenProject);
        addEjbClientArtifactConfiguration(module, projectConfig, mavenProject);
        resourceConfig.filteringExclusions.addAll(MavenProjectsTree.getFilterExclusions(mavenProject));
        final Properties properties = getFilteringProperties(mavenProject);
        for (Map.Entry<Object, Object> propEntry : properties.entrySet()) {
            resourceConfig.properties.put((String) propEntry.getKey(), (String) propEntry.getValue());
        }
        resourceConfig.escapeString = MavenJDOMUtil.findChildValueByPath(pluginConfiguration, "escapeString", null);
        String escapeWindowsPaths = MavenJDOMUtil.findChildValueByPath(pluginConfiguration, "escapeWindowsPaths");
        if (escapeWindowsPaths != null) {
            resourceConfig.escapeWindowsPaths = Boolean.parseBoolean(escapeWindowsPaths);
        }
        String overwrite = MavenJDOMUtil.findChildValueByPath(pluginConfiguration, "overwrite");
        if (overwrite != null) {
            resourceConfig.overwrite = Boolean.parseBoolean(overwrite);
        }
        projectConfig.moduleConfigurations.put(module.getName(), resourceConfig);
        generateManifest(mavenProject, module, resourceConfig);
    }
    addNonMavenResources(projectConfig);
    final Element element = new Element("maven-project-configuration");
    XmlSerializer.serializeInto(projectConfig, element);
    buildManager.runCommand(() -> {
        buildManager.clearState(myProject);
        FileUtil.createIfDoesntExist(mavenConfigFile);
        try {
            JdomKt.write(element, mavenConfigFile.toPath());
            DataOutputStream crcOutput = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(crcFile)));
            try {
                crcOutput.writeInt(crc);
            } finally {
                crcOutput.close();
            }
        } catch (IOException e) {
            LOG.debug("Unable to write config file", e);
            throw new RuntimeException(e);
        }
    });
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Element(org.jdom.Element) MavenId(org.jetbrains.idea.maven.model.MavenId) BuildManager(com.intellij.compiler.server.BuildManager) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile)

Aggregations

BuildManager (com.intellij.compiler.server.BuildManager)4 File (java.io.File)2 Element (org.jdom.Element)2 DefaultMessageHandler (com.intellij.compiler.server.DefaultMessageHandler)1 Module (com.intellij.openapi.module.Module)1 ProgressIndicator (com.intellij.openapi.progress.ProgressIndicator)1 Project (com.intellij.openapi.project.Project)1 MessageType (com.intellij.openapi.ui.MessageType)1 Key (com.intellij.openapi.util.Key)1 VirtualFile (com.intellij.openapi.vfs.VirtualFile)1 Artifact (com.intellij.packaging.artifacts.Artifact)1 FactoryMap (com.intellij.util.containers.FactoryMap)1 HashMap (com.intellij.util.containers.HashMap)1 MultiMap (com.intellij.util.containers.MultiMap)1 MessageBus (com.intellij.util.messages.MessageBus)1 THashMap (gnu.trove.THashMap)1 THashSet (gnu.trove.THashSet)1 IOException (java.io.IOException)1 Map (java.util.Map)1 Nullable (org.jetbrains.annotations.Nullable)1