Search in sources :

Example 1 with BuildEnvironment

use of org.gradle.tooling.model.build.BuildEnvironment in project gradle by gradle.

the class FetchBuildEnvironments method execute.

@Override
public List<BuildEnvironment> execute(BuildController controller) {
    List<BuildEnvironment> environments = new ArrayList<BuildEnvironment>();
    GradleBuild build = controller.getBuildModel();
    environments.add(controller.getModel(build, BuildEnvironment.class));
    for (GradleBuild includedBuild : build.getIncludedBuilds()) {
        environments.add(controller.getModel(includedBuild, BuildEnvironment.class));
    }
    return environments;
}
Also used : BuildEnvironment(org.gradle.tooling.model.build.BuildEnvironment) ArrayList(java.util.ArrayList) GradleBuild(org.gradle.tooling.model.gradle.GradleBuild)

Example 2 with BuildEnvironment

use of org.gradle.tooling.model.build.BuildEnvironment in project intellij-community by JetBrains.

the class GradleExecutionHelper method prepare.

@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
public static void prepare(@NotNull LongRunningOperation operation, @NotNull final ExternalSystemTaskId id, @NotNull GradleExecutionSettings settings, @NotNull final ExternalSystemTaskNotificationListener listener, @NotNull ProjectConnection connection, @NotNull final OutputStream standardOutput, @NotNull final OutputStream standardError) {
    Set<String> jvmArgs = settings.getVmOptions();
    if (!jvmArgs.isEmpty()) {
        // merge gradle args e.g. defined in gradle.properties
        BuildEnvironment buildEnvironment = getBuildEnvironment(connection);
        Collection<String> merged = buildEnvironment != null ? mergeJvmArgs(settings.getServiceDirectory(), buildEnvironment.getJava().getJvmArguments(), jvmArgs) : jvmArgs;
        // filter nulls and empty strings
        List<String> filteredArgs = ContainerUtil.mapNotNull(merged, s -> StringUtil.isEmpty(s) ? null : s);
        operation.setJvmArguments(ArrayUtil.toStringArray(filteredArgs));
    }
    if (settings.isOfflineWork()) {
        settings.withArgument(GradleConstants.OFFLINE_MODE_CMD_OPTION);
    }
    final Application application = ApplicationManager.getApplication();
    if (application != null && application.isUnitTestMode()) {
        if (!settings.getArguments().contains("--quiet")) {
            settings.withArgument("--info");
        }
        settings.withArgument("--recompile-scripts");
    }
    if (!settings.getArguments().isEmpty()) {
        LOG.info("Passing command-line args to Gradle Tooling API: " + StringUtil.join(settings.getArguments(), " "));
        // filter nulls and empty strings
        List<String> filteredArgs = ContainerUtil.mapNotNull(settings.getArguments(), s -> StringUtil.isEmpty(s) ? null : s);
        // TODO remove this replacement when --tests option will become available for tooling API
        replaceTestCommandOptionWithInitScript(filteredArgs);
        operation.withArguments(ArrayUtil.toStringArray(filteredArgs));
    }
    final String javaHome = settings.getJavaHome();
    if (javaHome != null && new File(javaHome).isDirectory()) {
        operation.setJavaHome(new File(javaHome));
    }
    operation.addProgressListener(new ProgressListener() {

        @Override
        public void statusChanged(ProgressEvent event) {
            listener.onStatusChange(new ExternalSystemTaskNotificationEvent(id, event.getDescription()));
        }
    });
    operation.addProgressListener(new org.gradle.tooling.events.ProgressListener() {

        @Override
        public void statusChanged(org.gradle.tooling.events.ProgressEvent event) {
            listener.onStatusChange(GradleProgressEventConverter.convert(id, event));
        }
    });
    operation.setStandardOutput(standardOutput);
    operation.setStandardError(standardError);
}
Also used : ExternalSystemTaskNotificationEvent(com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationEvent) BuildEnvironment(org.gradle.tooling.model.build.BuildEnvironment) Application(com.intellij.openapi.application.Application) File(java.io.File)

Example 3 with BuildEnvironment

use of org.gradle.tooling.model.build.BuildEnvironment in project intellij-community by JetBrains.

the class GradleExecutionHelper method getGradleVersion.

@Nullable
public static GradleVersion getGradleVersion(@NotNull ProjectConnection connection) {
    final BuildEnvironment buildEnvironment = getBuildEnvironment(connection);
    GradleVersion gradleVersion = null;
    if (buildEnvironment != null) {
        gradleVersion = GradleVersion.version(buildEnvironment.getGradle().getGradleVersion());
    }
    return gradleVersion;
}
Also used : BuildEnvironment(org.gradle.tooling.model.build.BuildEnvironment) GradleVersion(org.gradle.util.GradleVersion) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with BuildEnvironment

use of org.gradle.tooling.model.build.BuildEnvironment in project intellij-community by JetBrains.

the class GradleProjectResolver method doResolveProjectInfo.

@NotNull
private DataNode<ProjectData> doResolveProjectInfo(@NotNull final DefaultProjectResolverContext resolverCtx, @NotNull final GradleProjectResolverExtension projectResolverChain, boolean isBuildSrcProject) throws IllegalArgumentException, IllegalStateException {
    final BuildEnvironment buildEnvironment = GradleExecutionHelper.getBuildEnvironment(resolverCtx.getConnection());
    GradleVersion gradleVersion = null;
    boolean isGradleProjectDirSupported = false;
    boolean isCompositeBuildsSupported = false;
    if (buildEnvironment != null) {
        gradleVersion = GradleVersion.version(buildEnvironment.getGradle().getGradleVersion());
        isGradleProjectDirSupported = gradleVersion.compareTo(GradleVersion.version("2.4")) >= 0;
        isCompositeBuildsSupported = isGradleProjectDirSupported && gradleVersion.compareTo(GradleVersion.version("3.1")) >= 0;
    }
    final ProjectImportAction projectImportAction = new ProjectImportAction(resolverCtx.isPreviewMode(), isGradleProjectDirSupported, isCompositeBuildsSupported);
    GradleExecutionSettings executionSettings = resolverCtx.getSettings();
    if (executionSettings == null) {
        executionSettings = new GradleExecutionSettings(null, null, DistributionType.BUNDLED, false);
    }
    executionSettings.withArgument("-Didea.version=" + getIdeaVersion());
    if (resolverCtx.isPreviewMode()) {
        executionSettings.withArgument("-Didea.isPreviewMode=true");
        final Set<Class> previewLightWeightToolingModels = ContainerUtil.set(ExternalProjectPreview.class, GradleBuild.class);
        projectImportAction.addExtraProjectModelClasses(previewLightWeightToolingModels);
    }
    if (resolverCtx.isResolveModulePerSourceSet()) {
        executionSettings.withArgument("-Didea.resolveSourceSetDependencies=true");
    }
    if (!isBuildSrcProject) {
        for (GradleBuildParticipant buildParticipant : executionSettings.getExecutionWorkspace().getBuildParticipants()) {
            executionSettings.withArguments(GradleConstants.INCLUDE_BUILD_CMD_OPTION, buildParticipant.getProjectPath());
        }
    }
    final Set<Class> toolingExtensionClasses = ContainerUtil.newHashSet();
    final GradleImportCustomizer importCustomizer = GradleImportCustomizer.get();
    for (GradleProjectResolverExtension resolverExtension = projectResolverChain; resolverExtension != null; resolverExtension = resolverExtension.getNext()) {
        // inject ProjectResolverContext into gradle project resolver extensions
        resolverExtension.setProjectResolverContext(resolverCtx);
        // pre-import checks
        resolverExtension.preImportCheck();
        if (!resolverCtx.isPreviewMode()) {
            // register classes of extra gradle project models required for extensions (e.g. com.android.builder.model.AndroidProject)
            projectImportAction.addExtraProjectModelClasses(resolverExtension.getExtraProjectModelClasses());
        }
        if (importCustomizer == null || importCustomizer.useExtraJvmArgs()) {
            // collect extra JVM arguments provided by gradle project resolver extensions
            final ParametersList parametersList = new ParametersList();
            for (Pair<String, String> jvmArg : resolverExtension.getExtraJvmArgs()) {
                parametersList.addProperty(jvmArg.first, jvmArg.second);
            }
            executionSettings.withVmOptions(parametersList.getParameters());
        }
        // collect extra command-line arguments
        executionSettings.withArguments(resolverExtension.getExtraCommandLineArgs());
        // collect tooling extensions classes
        toolingExtensionClasses.addAll(resolverExtension.getToolingExtensionsClasses());
    }
    BuildActionExecuter<ProjectImportAction.AllModels> buildActionExecutor = resolverCtx.getConnection().action(projectImportAction);
    File initScript = GradleExecutionHelper.generateInitScript(isBuildSrcProject, toolingExtensionClasses);
    if (initScript != null) {
        executionSettings.withArguments(GradleConstants.INIT_SCRIPT_CMD_OPTION, initScript.getAbsolutePath());
    }
    GradleExecutionHelper.prepare(buildActionExecutor, resolverCtx.getExternalSystemTaskId(), executionSettings, resolverCtx.getListener(), resolverCtx.getConnection());
    resolverCtx.checkCancelled();
    ProjectImportAction.AllModels allModels;
    final CancellationTokenSource cancellationTokenSource = GradleConnector.newCancellationTokenSource();
    final long startTime = System.currentTimeMillis();
    try {
        resolverCtx.setCancellationTokenSource(cancellationTokenSource);
        buildActionExecutor.withCancellationToken(cancellationTokenSource.token());
        synchronized (myCancellationMap) {
            myCancellationMap.putValue(resolverCtx.getExternalSystemTaskId(), cancellationTokenSource);
            if (gradleVersion != null && gradleVersion.compareTo(GradleVersion.version("2.1")) < 0) {
                myCancellationMap.putValue(resolverCtx.getExternalSystemTaskId(), new UnsupportedCancellationToken());
            }
        }
        allModels = buildActionExecutor.run();
        if (allModels == null) {
            throw new IllegalStateException("Unable to get project model for the project: " + resolverCtx.getProjectPath());
        }
    } catch (UnsupportedVersionException unsupportedVersionException) {
        resolverCtx.checkCancelled();
        // Old gradle distribution version used (before ver. 1.8)
        // fallback to use ModelBuilder gradle tooling API
        Class<? extends IdeaProject> aClass = resolverCtx.isPreviewMode() ? BasicIdeaProject.class : IdeaProject.class;
        ModelBuilder<? extends IdeaProject> modelBuilder = myHelper.getModelBuilder(aClass, resolverCtx.getExternalSystemTaskId(), executionSettings, resolverCtx.getConnection(), resolverCtx.getListener());
        final IdeaProject ideaProject = modelBuilder.get();
        allModels = new ProjectImportAction.AllModels(ideaProject);
    } finally {
        final long timeInMs = (System.currentTimeMillis() - startTime);
        synchronized (myCancellationMap) {
            myCancellationMap.remove(resolverCtx.getExternalSystemTaskId(), cancellationTokenSource);
        }
        LOG.debug(String.format("Gradle data obtained in %d ms", timeInMs));
    }
    resolverCtx.checkCancelled();
    allModels.setBuildEnvironment(buildEnvironment);
    final long startDataConversionTime = System.currentTimeMillis();
    extractExternalProjectModels(allModels, resolverCtx);
    // import project data
    ProjectData projectData = projectResolverChain.createProject();
    DataNode<ProjectData> projectDataNode = new DataNode<>(ProjectKeys.PROJECT, projectData, null);
    // import java project data
    JavaProjectData javaProjectData = projectResolverChain.createJavaProjectData();
    projectDataNode.createChild(JavaProjectData.KEY, javaProjectData);
    IdeaProject ideaProject = resolverCtx.getModels().getIdeaProject();
    projectResolverChain.populateProjectExtraModels(ideaProject, projectDataNode);
    DomainObjectSet<? extends IdeaModule> gradleModules = ideaProject.getModules();
    if (gradleModules == null || gradleModules.isEmpty()) {
        throw new IllegalStateException("No modules found for the target project: " + ideaProject);
    }
    Collection<IdeaModule> includedModules = exposeCompositeBuild(allModels, resolverCtx, projectDataNode);
    final Map<String, Pair<DataNode<ModuleData>, IdeaModule>> /* module id */
    moduleMap = ContainerUtilRt.newHashMap();
    final Map<String, Pair<DataNode<GradleSourceSetData>, ExternalSourceSet>> /* module id */
    sourceSetsMap = ContainerUtil.newHashMap();
    projectDataNode.putUserData(RESOLVED_SOURCE_SETS, sourceSetsMap);
    final Map<String, Pair<String, ExternalSystemSourceType>> /* module id*/
    moduleOutputsMap = ContainerUtil.newTroveMap(FileUtil.PATH_HASHING_STRATEGY);
    projectDataNode.putUserData(MODULES_OUTPUTS, moduleOutputsMap);
    final Map<String, String> /* module id*/
    artifactsMap = ContainerUtil.newTroveMap(FileUtil.PATH_HASHING_STRATEGY);
    projectDataNode.putUserData(CONFIGURATION_ARTIFACTS, artifactsMap);
    // import modules data
    for (IdeaModule gradleModule : ContainerUtil.concat(gradleModules, includedModules)) {
        if (gradleModule == null) {
            continue;
        }
        resolverCtx.checkCancelled();
        if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
            LOG.info(String.format("Importing module data: %s", gradleModule));
        }
        final String moduleName = gradleModule.getName();
        if (moduleName == null) {
            throw new IllegalStateException("Module with undefined name detected: " + gradleModule);
        }
        DataNode<ModuleData> moduleDataNode = projectResolverChain.createModule(gradleModule, projectDataNode);
        String mainModuleId = getModuleId(resolverCtx, gradleModule);
        if (moduleMap.containsKey(mainModuleId)) {
            // we should ensure deduplicated module names in the scope of single import
            throw new IllegalStateException("Duplicate modules names detected: " + gradleModule);
        }
        moduleMap.put(mainModuleId, Pair.create(moduleDataNode, gradleModule));
    }
    executionSettings.getExecutionWorkspace().addModuleMap(moduleMap);
    File gradleHomeDir = null;
    // populate modules nodes
    for (final Pair<DataNode<ModuleData>, IdeaModule> pair : moduleMap.values()) {
        final DataNode<ModuleData> moduleDataNode = pair.first;
        final IdeaModule ideaModule = pair.second;
        if (gradleHomeDir == null) {
            final BuildScriptClasspathModel buildScriptClasspathModel = resolverCtx.getExtraProject(ideaModule, BuildScriptClasspathModel.class);
            if (buildScriptClasspathModel != null) {
                gradleHomeDir = buildScriptClasspathModel.getGradleHomeDir();
            }
        }
        projectResolverChain.populateModuleContentRoots(ideaModule, moduleDataNode);
        projectResolverChain.populateModuleCompileOutputSettings(ideaModule, moduleDataNode);
        if (!isBuildSrcProject) {
            projectResolverChain.populateModuleTasks(ideaModule, moduleDataNode, projectDataNode);
        }
        final List<DataNode<? extends ModuleData>> modules = ContainerUtil.newSmartList();
        modules.add(moduleDataNode);
        modules.addAll(ExternalSystemApiUtil.findAll(moduleDataNode, GradleSourceSetData.KEY));
        final ExternalSystemSourceType[] sourceTypes = new ExternalSystemSourceType[] { ExternalSystemSourceType.SOURCE, ExternalSystemSourceType.RESOURCE, ExternalSystemSourceType.TEST, ExternalSystemSourceType.TEST_RESOURCE };
        for (DataNode<? extends ModuleData> module : modules) {
            final ModuleData moduleData = module.getData();
            for (ExternalSystemSourceType sourceType : sourceTypes) {
                final String path = moduleData.getCompileOutputPath(sourceType);
                if (path != null) {
                    moduleOutputsMap.put(path, Pair.create(moduleData.getId(), sourceType));
                }
            }
            if (moduleData instanceof GradleSourceSetData) {
                for (File artifactFile : moduleData.getArtifacts()) {
                    artifactsMap.put(ExternalSystemApiUtil.toCanonicalPath(artifactFile.getAbsolutePath()), moduleData.getId());
                }
            }
        }
    }
    for (final Pair<DataNode<ModuleData>, IdeaModule> pair : moduleMap.values()) {
        final DataNode<ModuleData> moduleDataNode = pair.first;
        final IdeaModule ideaModule = pair.second;
        projectResolverChain.populateModuleDependencies(ideaModule, moduleDataNode, projectDataNode);
        projectResolverChain.populateModuleExtraModels(ideaModule, moduleDataNode);
    }
    mergeSourceSetContentRoots(moduleMap, resolverCtx);
    if (resolverCtx.isResolveModulePerSourceSet()) {
        mergeLibraryAndModuleDependencyData(projectDataNode, gradleHomeDir, gradleVersion);
    }
    projectDataNode.putUserData(RESOLVED_SOURCE_SETS, null);
    projectDataNode.putUserData(MODULES_OUTPUTS, null);
    projectDataNode.putUserData(CONFIGURATION_ARTIFACTS, null);
    // ensure unique library names
    Collection<DataNode<LibraryData>> libraries = ExternalSystemApiUtil.getChildren(projectDataNode, ProjectKeys.LIBRARY);
    myLibraryNamesMixer.mixNames(libraries);
    final long timeConversionInMs = (System.currentTimeMillis() - startDataConversionTime);
    LOG.debug(String.format("Project data resolved in %d ms", timeConversionInMs));
    return projectDataNode;
}
Also used : GradleExecutionSettings(org.jetbrains.plugins.gradle.settings.GradleExecutionSettings) IdeaProject(org.gradle.tooling.model.idea.IdeaProject) BasicIdeaProject(org.gradle.tooling.model.idea.BasicIdeaProject) JavaProjectData(com.intellij.externalSystem.JavaProjectData) GradleSourceSetData(org.jetbrains.plugins.gradle.model.data.GradleSourceSetData) UnsupportedCancellationToken(org.jetbrains.plugins.gradle.service.execution.UnsupportedCancellationToken) ParametersList(com.intellij.execution.configurations.ParametersList) IdeaModule(org.gradle.tooling.model.idea.IdeaModule) DataNode(com.intellij.openapi.externalSystem.model.DataNode) GradleVersion(org.gradle.util.GradleVersion) JavaProjectData(com.intellij.externalSystem.JavaProjectData) Pair(com.intellij.openapi.util.Pair) BasicIdeaProject(org.gradle.tooling.model.idea.BasicIdeaProject) BuildEnvironment(org.gradle.tooling.model.build.BuildEnvironment) GradleBuildParticipant(org.jetbrains.plugins.gradle.settings.GradleBuildParticipant) File(java.io.File) NotNull(org.jetbrains.annotations.NotNull)

Example 5 with BuildEnvironment

use of org.gradle.tooling.model.build.BuildEnvironment in project intellij-community by JetBrains.

the class ProjectImportAction method execute.

@Nullable
@Override
public AllModels execute(final BuildController controller) {
    configureAdditionalTypes(controller);
    //outer conditional is needed to be compatible with 1.8
    final IdeaProject ideaProject = myIsPreviewMode ? controller.getModel(BasicIdeaProject.class) : controller.getModel(IdeaProject.class);
    if (ideaProject == null || ideaProject.getModules().isEmpty()) {
        return null;
    }
    AllModels allModels = new AllModels(ideaProject);
    allModels.setGradleProjectDirSupported(myIsGradleProjectDirSupported);
    BuildEnvironment buildEnvironment = controller.findModel(BuildEnvironment.class);
    allModels.setBuildEnvironment(buildEnvironment);
    addExtraProject(controller, allModels, null);
    for (IdeaModule module : ideaProject.getModules()) {
        addExtraProject(controller, allModels, module);
    }
    if (myIsCompositeBuildsSupported) {
        GradleBuild gradleBuild = controller.getModel(GradleBuild.class);
        for (GradleBuild build : gradleBuild.getIncludedBuilds()) {
            IdeaProject ideaIncludedProject = controller.findModel(build, IdeaProject.class);
            allModels.getIncludedBuilds().add(ideaIncludedProject);
            for (IdeaModule module : ideaIncludedProject.getModules()) {
                addExtraProject(controller, allModels, module);
            }
        }
    }
    return allModels;
}
Also used : IdeaProject(org.gradle.tooling.model.idea.IdeaProject) BasicIdeaProject(org.gradle.tooling.model.idea.BasicIdeaProject) IdeaModule(org.gradle.tooling.model.idea.IdeaModule) BuildEnvironment(org.gradle.tooling.model.build.BuildEnvironment) BasicIdeaProject(org.gradle.tooling.model.idea.BasicIdeaProject) GradleBuild(org.gradle.tooling.model.gradle.GradleBuild) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

BuildEnvironment (org.gradle.tooling.model.build.BuildEnvironment)6 Nullable (org.jetbrains.annotations.Nullable)3 File (java.io.File)2 GradleBuild (org.gradle.tooling.model.gradle.GradleBuild)2 BasicIdeaProject (org.gradle.tooling.model.idea.BasicIdeaProject)2 IdeaModule (org.gradle.tooling.model.idea.IdeaModule)2 IdeaProject (org.gradle.tooling.model.idea.IdeaProject)2 GradleVersion (org.gradle.util.GradleVersion)2 ParametersList (com.intellij.execution.configurations.ParametersList)1 JavaProjectData (com.intellij.externalSystem.JavaProjectData)1 Application (com.intellij.openapi.application.Application)1 DataNode (com.intellij.openapi.externalSystem.model.DataNode)1 ExternalSystemException (com.intellij.openapi.externalSystem.model.ExternalSystemException)1 ExternalSystemTaskNotificationEvent (com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationEvent)1 Pair (com.intellij.openapi.util.Pair)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 NotNull (org.jetbrains.annotations.NotNull)1 GradleSourceSetData (org.jetbrains.plugins.gradle.model.data.GradleSourceSetData)1 UnsupportedCancellationToken (org.jetbrains.plugins.gradle.service.execution.UnsupportedCancellationToken)1