Search in sources :

Example 1 with IdeaModule

use of org.gradle.plugins.ide.idea.model.IdeaModule in project intellij-community by JetBrains.

the class ModelBuildScriptClasspathBuilderImpl method buildAll.

@Nullable
@Override
public Object buildAll(final String modelName, final Project project) {
    BuildScriptClasspathModelImpl buildScriptClasspath = cache.get(project.getPath());
    if (buildScriptClasspath != null)
        return buildScriptClasspath;
    if (mySourceSetFinder == null)
        mySourceSetFinder = new SourceSetCachedFinder(project);
    buildScriptClasspath = new BuildScriptClasspathModelImpl();
    final File gradleHomeDir = project.getGradle().getGradleHomeDir();
    buildScriptClasspath.setGradleHomeDir(gradleHomeDir);
    buildScriptClasspath.setGradleVersion(GradleVersion.current().getVersion());
    boolean downloadJavadoc = false;
    boolean downloadSources = true;
    final IdeaPlugin ideaPlugin = project.getPlugins().findPlugin(IdeaPlugin.class);
    if (ideaPlugin != null) {
        final IdeaModule ideaModule = ideaPlugin.getModel().getModule();
        downloadJavadoc = ideaModule.isDownloadJavadoc();
        downloadSources = ideaModule.isDownloadSources();
    }
    Project parent = project.getParent();
    if (parent != null) {
        BuildScriptClasspathModelImpl parentBuildScriptClasspath = (BuildScriptClasspathModelImpl) buildAll(modelName, parent);
        if (parentBuildScriptClasspath != null) {
            for (ClasspathEntryModel classpathEntryModel : parentBuildScriptClasspath.getClasspath()) {
                buildScriptClasspath.add(classpathEntryModel);
            }
        }
    }
    Configuration classpathConfiguration = project.getBuildscript().getConfigurations().findByName(CLASSPATH_CONFIGURATION_NAME);
    if (classpathConfiguration == null)
        return null;
    Collection<ExternalDependency> dependencies = new DependencyResolverImpl(project, false, downloadJavadoc, downloadSources, mySourceSetFinder).resolveDependencies(classpathConfiguration);
    for (ExternalDependency dependency : new DependencyTraverser(dependencies)) {
        if (dependency instanceof ExternalLibraryDependency) {
            final ExternalLibraryDependency libraryDep = (ExternalLibraryDependency) dependency;
            buildScriptClasspath.add(new ClasspathEntryModelImpl(pathSet(libraryDep.getFile()), pathSet(libraryDep.getSource()), pathSet(libraryDep.getJavadoc())));
        }
        if (dependency instanceof ExternalMultiLibraryDependency) {
            ExternalMultiLibraryDependency multiLibraryDependency = (ExternalMultiLibraryDependency) dependency;
            buildScriptClasspath.add(new ClasspathEntryModelImpl(pathSet(multiLibraryDependency.getFiles()), pathSet(multiLibraryDependency.getSources()), pathSet(multiLibraryDependency.getJavadoc())));
        }
        if (dependency instanceof FileCollectionDependency) {
            FileCollectionDependency fileCollectionDependency = (FileCollectionDependency) dependency;
            buildScriptClasspath.add(new ClasspathEntryModelImpl(pathSet(fileCollectionDependency.getFiles()), new HashSet<String>(), new HashSet<String>()));
        }
    }
    cache.put(project.getPath(), buildScriptClasspath);
    return buildScriptClasspath;
}
Also used : BuildScriptClasspathModelImpl(org.jetbrains.plugins.gradle.tooling.internal.BuildScriptClasspathModelImpl) Configuration(org.gradle.api.artifacts.Configuration) IdeaPlugin(org.gradle.plugins.ide.idea.IdeaPlugin) SourceSetCachedFinder(org.jetbrains.plugins.gradle.tooling.util.SourceSetCachedFinder) DependencyTraverser(org.jetbrains.plugins.gradle.tooling.util.DependencyTraverser) ClasspathEntryModelImpl(org.jetbrains.plugins.gradle.tooling.internal.ClasspathEntryModelImpl) Project(org.gradle.api.Project) IdeaModule(org.gradle.plugins.ide.idea.model.IdeaModule) DependencyResolverImpl(org.jetbrains.plugins.gradle.tooling.util.DependencyResolverImpl) File(java.io.File) Nullable(org.jetbrains.annotations.Nullable)

Example 2 with IdeaModule

use of org.gradle.plugins.ide.idea.model.IdeaModule in project gradle by gradle.

the class IdeaPlugin method configureIdeaModule.

private void configureIdeaModule(final Project project) {
    final GenerateIdeaModule task = project.getTasks().create("ideaModule", GenerateIdeaModule.class);
    task.setDescription("Generates IDEA module files (IML)");
    IdeaModuleIml iml = new IdeaModuleIml(task.getXmlTransformer(), project.getProjectDir());
    final IdeaModule module = instantiator.newInstance(IdeaModule.class, project, iml);
    task.setModule(module);
    ideaModel.setModule(module);
    ConventionMapping conventionMapping = ((IConventionAware) module).getConventionMapping();
    conventionMapping.map("sourceDirs", new Callable<Set<File>>() {

        @Override
        public Set<File> call() throws Exception {
            return Sets.newHashSet();
        }
    });
    conventionMapping.map("name", new Callable<String>() {

        @Override
        public String call() throws Exception {
            return project.getName();
        }
    });
    conventionMapping.map("contentRoot", new Callable<File>() {

        @Override
        public File call() throws Exception {
            return project.getProjectDir();
        }
    });
    conventionMapping.map("testSourceDirs", new Callable<Set<File>>() {

        @Override
        public Set<File> call() throws Exception {
            return Sets.newHashSet();
        }
    });
    conventionMapping.map("excludeDirs", new Callable<Set<File>>() {

        @Override
        public Set<File> call() throws Exception {
            return Sets.newHashSet(project.getBuildDir(), project.file(".gradle"));
        }
    });
    conventionMapping.map("pathFactory", new Callable<PathFactory>() {

        @Override
        public PathFactory call() throws Exception {
            final PathFactory factory = new PathFactory();
            factory.addPathVariable("MODULE_DIR", task.getOutputFile().getParentFile());
            for (Map.Entry<String, File> entry : module.getPathVariables().entrySet()) {
                factory.addPathVariable(entry.getKey(), entry.getValue());
            }
            return factory;
        }
    });
    addWorker(task);
}
Also used : Set(java.util.Set) PathFactory(org.gradle.plugins.ide.idea.model.PathFactory) ConventionMapping(org.gradle.api.internal.ConventionMapping) IdeaModule(org.gradle.plugins.ide.idea.model.IdeaModule) IdeaModuleIml(org.gradle.plugins.ide.idea.model.IdeaModuleIml) IConventionAware(org.gradle.api.internal.IConventionAware) File(java.io.File)

Example 3 with IdeaModule

use of org.gradle.plugins.ide.idea.model.IdeaModule in project curiostack by curioswitch.

the class CuriostackPlugin method setupJavaProject.

private static void setupJavaProject(Project project) {
    PluginContainer plugins = project.getPlugins();
    plugins.apply(AptPlugin.class);
    plugins.apply(AptIdeaPlugin.class);
    plugins.apply(BaselineIdea.class);
    plugins.apply(DependencyManagementPlugin.class);
    plugins.apply(ErrorPronePlugin.class);
    plugins.apply(LicensePlugin.class);
    plugins.apply(SpotlessPlugin.class);
    plugins.apply(VersionsPlugin.class);
    project.getTasks().withType(JavaCompile.class, task -> {
        task.getOptions().setIncremental(true);
        task.getOptions().getCompilerArgs().addAll(ImmutableList.of("-XepDisableWarningsInGeneratedCode", "-XepExcludedPaths:(.*/build/.*|.*/gen-src/.*)", "-Xep:AutoFactoryAtInject:ERROR", "-Xep:ClassName:ERROR", "-Xep:ComparisonContractViolated:ERROR", "-Xep:DepAnn:ERROR", "-Xep:DivZero:ERROR", "-Xep:EmptyIf:ERROR", "-Xep:FuzzyEqualsShouldNotBeUsedInEqualsMethod:ERROR", "-Xep:InjectInvalidTargetingOnScopingAnnotation:ERROR", "-Xep:InjectScopeAnnotationOnInterfaceOrAbstractClass:ERROR", "-Xep:InsecureCryptoUsage:ERROR", "-Xep:IterablePathParameter:ERROR", "-Xep:LongLiteralLowerCaseSuffix:ERROR", "-Xep:NumericEquality:ERROR", "-Xep:ParameterPackage:ERROR", "-Xep:ProtoStringFieldReferenceEquality:ERROR", "-Xep:AssistedInjectAndInjectOnConstructors:ERROR", "-Xep:BigDecimalLiteralDouble:ERROR", "-Xep:ConstructorLeaksThis:ERROR", "-Xep:InconsistentOverloads:ERROR", "-Xep:MissingDefault:ERROR", "-Xep:PrimitiveArrayPassedToVarargsMethod:ERROR", "-Xep:RedundantThrows:ERROR", "-Xep:StaticQualifiedUsingExpression:ERROR", "-Xep:StringEquality:ERROR", "-Xep:TestExceptionChecker:ERROR", "-Xep:FieldMissingNullable:ERROR", "-Xep:LambdaFunctionalInterface:ERROR", "-Xep:MethodCanBeStatic:ERROR", "-Xep:MixedArrayDimensions:ERROR", "-Xep:MultiVariableDeclaration:ERROR", "-Xep:MultipleTopLevelClasses:ERROR", "-Xep:MultipleUnaryOperatorsInMethodCall:ERROR", "-Xep:PackageLocation:ERROR", "-Xep:ParameterComment:ERROR", "-Xep:ParameterNotNullable:ERROR", "-Xep:PrivateConstructorForUtilityClass:ERROR", "-Xep:RemoveUnusedImports:ERROR", "-Xep:ReturnMissingNullable:ERROR", "-Xep:SwitchDefault:ERROR", "-Xep:ThrowsUncheckedException:ERROR", "-Xep:UngroupedOverloads:ERROR", "-Xep:UnnecessaryStaticImport:ERROR", "-Xep:UseBinds:ERROR", "-Xep:WildcardImport:ERROR"));
        project.getTasks().withType(SpotlessTask.class, spotlessTask -> spotlessTask.dependsOn(task));
    });
    JavaPluginConvention javaPlugin = project.getConvention().getPlugin(JavaPluginConvention.class);
    javaPlugin.setSourceCompatibility(JavaVersion.VERSION_1_9);
    javaPlugin.setTargetCompatibility(JavaVersion.VERSION_1_9);
    Test test = project.getTasks().withType(Test.class).getByName("test");
    if (project.getRootProject().hasProperty("updateSnapshots")) {
        test.jvmArgs(ImmutableList.of("-Dorg.curioswitch.testing.updateSnapshots=true"));
    }
    test.useJUnitPlatform(platform -> platform.includeEngines("junit-jupiter", "junit-vintage"));
    // While Gradle attempts to generate a unique module name automatically,
    // it doesn't seem to always work properly, so we just always use unique
    // module names.
    project.getPlugins().withType(IdeaPlugin.class, plugin -> {
        IdeaModule module = plugin.getModel().getModule();
        String moduleName = project.getName();
        Project ancestor = project.getParent();
        while (ancestor != null && ancestor != project.getRootProject()) {
            moduleName = ancestor.getName() + "-" + moduleName;
            ancestor = ancestor.getParent();
        }
        module.setName(moduleName);
        project.getTasks().getByName("clean").doLast(unused -> project.file(project.getName() + ".iml").delete());
        new DslObject(module).getConvention().getPlugin(ModuleAptConvention.class).getApt().setAddAptDependencies(false);
    });
    DependencyManagementExtension dependencyManagement = project.getExtensions().getByType(DependencyManagementExtension.class);
    dependencyManagement.dependencies(dependencies -> {
        for (DependencySet set : StandardDependencies.DEPENDENCY_SETS) {
            dependencies.dependencySet(ImmutableMap.of("group", set.group(), "version", set.version()), dependencySet -> set.modules().forEach(dependencySet::entry));
        }
        StandardDependencies.DEPENDENCIES.forEach(dependencies::dependency);
    });
    // Pretty much all java code needs at least the Generated annotation.
    project.getDependencies().add(JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME, "javax.annotation:javax.annotation-api");
    project.afterEvaluate(CuriostackPlugin::addStandardJavaTestDependencies);
    project.getConfigurations().all(configuration -> configuration.exclude(ImmutableMap.of("group", "com.google.guava", "module", "guava-jdk5")));
    Javadoc javadoc = (Javadoc) project.getTasks().getByName("javadoc");
    CoreJavadocOptions options = (CoreJavadocOptions) javadoc.getOptions();
    options.quiet();
    options.addBooleanOption("Xdoclint:all,-missing", true);
    project.getTasks().create("javadocJar", Jar.class, javadocJar -> {
        javadocJar.dependsOn(javadoc);
        javadocJar.setClassifier("javadoc");
        javadocJar.from(javadoc.getDestinationDir());
    });
    SourceSetContainer sourceSets = javaPlugin.getSourceSets();
    project.getTasks().create("sourceJar", Jar.class, sourceJar -> {
        sourceJar.setClassifier("sources");
        sourceJar.from(sourceSets.getByName(SourceSet.MAIN_SOURCE_SET_NAME).getAllSource());
    });
    SpotlessExtension spotless = project.getExtensions().getByType(SpotlessExtension.class);
    spotless.java((extension) -> extension.googleJavaFormat(GOOGLE_JAVA_FORMAT_VERSION));
    project.getTasks().create("resolveDependencies", resolveDependencies -> resolveDependencies.doLast(unused -> {
        project.getConfigurations().all(configuration -> {
            if (configuration.isCanBeResolved()) {
                configuration.resolve();
            }
        });
    }));
    // Protobuf plugin doesn't add proto sourceset to allSource, which seems like an omission.
    // We add it to make sure license plugin picks up the files.
    project.getPlugins().withType(ProtobufPlugin.class, unused -> {
        for (SourceSet sourceSet : sourceSets) {
            sourceSet.getAllSource().source(((ExtensionAware) sourceSet).getExtensions().getByType(ProtobufSourceDirectorySet.class));
        }
    });
    project.getPlugins().withType(JMHPlugin.class, unused -> {
        JMHPluginExtension jmh = project.getExtensions().getByType(JMHPluginExtension.class);
        // Benchmarks are usually very small and converge quickly. If this stops being the
        // case
        // these numbers can be adjusted.
        jmh.setFork(2);
        jmh.setIterations(5);
        jmh.setProfilers(ImmutableList.of("hs_comp"));
        jmh.setJmhVersion("1.19");
        Object jmhRegex = project.getRootProject().findProperty("jmhRegex");
        if (jmhRegex != null) {
            jmh.setInclude((String) jmhRegex);
        }
        // We will use the jmhManaged for any dependencies that should only be applied to JMH
        // but should be resolved by our managed dependencies. We need a separate
        // configuration
        // to be able to provide the resolution workaround described below.
        Configuration jmhManaged = project.getConfigurations().create("jmhManaged");
        Configuration jmhConfiguration = project.getConfigurations().getByName("jmh");
        jmhConfiguration.extendsFrom(jmhManaged);
        // JMH plugin uses a detached configuration to build an uber-jar, which
        // dependencyManagement
        // doesn't know about. Work around this by forcing parent configurations to be
        // resolved and
        // added directly to the jmh configuration, which overwrites the otherwise
        // unresolvable
        // dependency.
        project.afterEvaluate(p -> {
            jmhConfiguration.getExtendsFrom().forEach(parent -> {
                parent.getResolvedConfiguration().getFirstLevelModuleDependencies().forEach(dep -> {
                    project.getDependencies().add("jmh", dep.getModule().toString());
                });
            });
        });
    });
    project.getPlugins().withType(JooqPlugin.class, unused -> {
        project.getTasks().withType(JooqTask.class, t -> {
            for (String dependency : ImmutableList.of("javax.activation:activation", "javax.xml.bind:jaxb-api", "com.sun.xml.bind:jaxb-core", "com.sun.xml.bind:jaxb-impl", "mysql:mysql-connector-java", // Not sure why this isn't automatically added.
            "com.google.guava:guava", "com.google.cloud.sql:mysql-socket-factory")) {
                project.getDependencies().add("jooqRuntime", dependency);
            }
        });
    });
    // It is very common to want to pass in command line system properties to the binary, so just
    // always forward properties. It won't affect production since no one runs binaries via Gradle
    // in production.
    project.getTasks().withType(JavaExec.class, task -> System.getProperties().entrySet().stream().filter(entry -> !entry.getKey().equals("java.endorsed.dirs")).forEach(entry -> task.systemProperty((String) entry.getKey(), entry.getValue())));
}
Also used : AptIdeaPlugin(net.ltgt.gradle.apt.AptIdeaPlugin) Closure(groovy.lang.Closure) JavaPlugin(org.gradle.api.plugins.JavaPlugin) IdeaPlugin(org.gradle.plugins.ide.idea.IdeaPlugin) ModuleAptConvention(net.ltgt.gradle.apt.AptIdeaPlugin.ModuleAptConvention) DependencyManagementPlugin(io.spring.gradle.dependencymanagement.DependencyManagementPlugin) DslObject(org.gradle.api.internal.plugins.DslObject) Task(org.gradle.api.Task) Javadoc(org.gradle.api.tasks.javadoc.Javadoc) YarnTask(com.moowork.gradle.node.yarn.YarnTask) Map(java.util.Map) LicensePlugin(nl.javadude.gradle.plugins.license.LicensePlugin) ExtensionAware(org.gradle.api.plugins.ExtensionAware) Splitter(com.google.common.base.Splitter) Path(java.nio.file.Path) PythonEnvsExtension(com.jetbrains.python.envs.PythonEnvsExtension) IdeaModule(org.gradle.plugins.ide.idea.model.IdeaModule) Delete(org.gradle.api.tasks.Delete) ImmutableMap(com.google.common.collect.ImmutableMap) Project(org.gradle.api.Project) NodeTask(com.moowork.gradle.node.task.NodeTask) Predicate(java.util.function.Predicate) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) ProtobufPlugin(com.google.protobuf.gradle.ProtobufPlugin) SetupGitHooks(org.curioswitch.gradle.plugins.curiostack.tasks.SetupGitHooks) SpotlessExtension(com.diffplug.gradle.spotless.SpotlessExtension) AptPlugin(net.ltgt.gradle.apt.AptPlugin) JavaVersion(org.gradle.api.JavaVersion) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) JavaLibraryPlugin(org.gradle.api.plugins.JavaLibraryPlugin) List(java.util.List) CoreJavadocOptions(org.gradle.external.javadoc.CoreJavadocOptions) VersionsPlugin(com.github.benmanes.gradle.versions.VersionsPlugin) YarnInstallTask(com.moowork.gradle.node.yarn.YarnInstallTask) BaselineIdea(com.palantir.baseline.plugins.BaselineIdea) ByteStreams(com.google.common.io.ByteStreams) Optional(java.util.Optional) PluginContainer(org.gradle.api.plugins.PluginContainer) ExecSpec(org.gradle.process.ExecSpec) DependencySet(org.curioswitch.gradle.plugins.curiostack.StandardDependencies.DependencySet) XmlProvider(org.gradle.api.XmlProvider) LicenseExtension(nl.javadude.gradle.plugins.license.LicenseExtension) JooqPlugin(nu.studer.gradle.jooq.JooqPlugin) CurioGenericCiPlugin(org.curioswitch.gradle.plugins.ci.CurioGenericCiPlugin) ErrorPronePlugin(net.ltgt.gradle.errorprone.ErrorPronePlugin) NodePlugin(com.moowork.gradle.node.NodePlugin) HashMap(java.util.HashMap) BasePlugin(org.gradle.api.plugins.BasePlugin) SourceSet(org.gradle.api.tasks.SourceSet) Configuration(org.gradle.api.artifacts.Configuration) JMHPluginExtension(me.champeau.gradle.JMHPluginExtension) ImmutableList(com.google.common.collect.ImmutableList) DependencyHandler(org.gradle.api.artifacts.dsl.DependencyHandler) DependencyManagementExtension(io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension) SourceSetContainer(org.gradle.api.tasks.SourceSetContainer) JooqTask(nu.studer.gradle.jooq.JooqTask) CreateShellConfigTask(org.curioswitch.gradle.plugins.curiostack.tasks.CreateShellConfigTask) NodeExtension(com.moowork.gradle.node.NodeExtension) Test(org.gradle.api.tasks.testing.Test) PythonEnvsPlugin(com.jetbrains.python.envs.PythonEnvsPlugin) JavaCompile(org.gradle.api.tasks.compile.JavaCompile) Resources(com.google.common.io.Resources) NpmTask(com.moowork.gradle.node.npm.NpmTask) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) Jar(org.gradle.jvm.tasks.Jar) FileOutputStream(java.io.FileOutputStream) JMHPlugin(me.champeau.gradle.JMHPlugin) SpotlessTask(com.diffplug.gradle.spotless.SpotlessTask) IOException(java.io.IOException) Node(groovy.util.Node) GcloudPlugin(org.curioswitch.gradle.plugins.gcloud.GcloudPlugin) File(java.io.File) SpotlessPlugin(com.diffplug.gradle.spotless.SpotlessPlugin) ProtobufSourceDirectorySet(com.google.protobuf.gradle.ProtobufSourceDirectorySet) Os(org.apache.tools.ant.taskdefs.condition.Os) Paths(java.nio.file.Paths) ResolutionRulesPlugin(nebula.plugin.resolutionrules.ResolutionRulesPlugin) CommandUtil(org.curioswitch.gradle.plugins.shared.CommandUtil) JavaExec(org.gradle.api.tasks.JavaExec) LambdaClosure(org.curioswitch.gradle.common.LambdaClosure) Plugin(org.gradle.api.Plugin) Copy(org.gradle.api.tasks.Copy) InputStream(java.io.InputStream) PluginContainer(org.gradle.api.plugins.PluginContainer) Configuration(org.gradle.api.artifacts.Configuration) DslObject(org.gradle.api.internal.plugins.DslObject) SpotlessExtension(com.diffplug.gradle.spotless.SpotlessExtension) DependencySet(org.curioswitch.gradle.plugins.curiostack.StandardDependencies.DependencySet) Javadoc(org.gradle.api.tasks.javadoc.Javadoc) DependencyManagementExtension(io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension) SourceSetContainer(org.gradle.api.tasks.SourceSetContainer) Project(org.gradle.api.Project) CoreJavadocOptions(org.gradle.external.javadoc.CoreJavadocOptions) SourceSet(org.gradle.api.tasks.SourceSet) IdeaModule(org.gradle.plugins.ide.idea.model.IdeaModule) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) Test(org.gradle.api.tasks.testing.Test) JMHPluginExtension(me.champeau.gradle.JMHPluginExtension) ExtensionAware(org.gradle.api.plugins.ExtensionAware) ProtobufSourceDirectorySet(com.google.protobuf.gradle.ProtobufSourceDirectorySet) DslObject(org.gradle.api.internal.plugins.DslObject)

Example 4 with IdeaModule

use of org.gradle.plugins.ide.idea.model.IdeaModule in project gradle by gradle.

the class IdeaPlugin method allImlArtifactsInComposite.

private List<TaskDependency> allImlArtifactsInComposite(ProjectInternal project, IdeaProject ideaProject) {
    List<TaskDependency> dependencies = Lists.newArrayList();
    ProjectComponentIdentifier thisProjectId = projectPathRegistry.getProjectComponentIdentifier(project.getIdentityPath());
    for (IdeArtifactRegistry.Reference<IdeaModuleMetadata> reference : artifactRegistry.getIdeArtifactMetadata(IdeaModuleMetadata.class)) {
        BuildIdentifier otherBuildId = reference.getOwningProject().getBuild();
        if (thisProjectId.getBuild().equals(otherBuildId)) {
            // IDEA Module for project in current build: don't include any module that has been excluded from project
            boolean found = false;
            for (IdeaModule ideaModule : ideaProject.getModules()) {
                if (reference.get().getFile().equals(ideaModule.getOutputFile())) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                continue;
            }
        }
        dependencies.add(reference.getBuildDependencies());
    }
    return dependencies;
}
Also used : TaskDependency(org.gradle.api.tasks.TaskDependency) IdeaModule(org.gradle.plugins.ide.idea.model.IdeaModule) IdeaModuleMetadata(org.gradle.plugins.ide.idea.internal.IdeaModuleMetadata) IdeArtifactRegistry(org.gradle.plugins.ide.internal.IdeArtifactRegistry) BuildIdentifier(org.gradle.api.artifacts.component.BuildIdentifier) ProjectComponentIdentifier(org.gradle.api.artifacts.component.ProjectComponentIdentifier)

Example 5 with IdeaModule

use of org.gradle.plugins.ide.idea.model.IdeaModule in project gradle-apt-plugin by tbroyer.

the class AptIdeaPlugin method configureIdeaModule.

private void configureIdeaModule(Project project, final SourceSet mainSourceSet, final SourceSet testSourceSet) {
    final IdeaModule ideaModule = project.getExtensions().getByType(IdeaModel.class).getModule();
    final ModuleApt apt = new ModuleApt();
    new DslObject(ideaModule).getConvention().getPlugins().put("net.ltgt.apt-idea", new ModuleAptConvention(apt));
    project.afterEvaluate(new Action<Project>() {

        @Override
        public void execute(Project project) {
            if (apt.isAddGeneratedSourcesDirs()) {
                Set<File> excl = new LinkedHashSet<>();
                for (SourceSet sourceSet : new SourceSet[] { mainSourceSet, testSourceSet }) {
                    File generatedSourcesDir = new DslObject(sourceSet.getOutput()).getConvention().getPlugin(AptPlugin.AptSourceSetOutputConvention.class).getGeneratedSourcesDir();
                    for (File f = generatedSourcesDir; f != null && !f.equals(project.getProjectDir()); f = f.getParentFile()) {
                        excl.add(f);
                    }
                }
                // For some reason, modifying the existing collections doesn't work.
                // We need to copy the values and then assign it back.
                Set<File> excludeDirs = new LinkedHashSet<>(ideaModule.getExcludeDirs());
                if (excl.contains(project.getBuildDir()) && excludeDirs.contains(project.getBuildDir())) {
                    excludeDirs.remove(project.getBuildDir());
                    // Race condition: many of these will actually be created afterwards…
                    File[] subdirs = project.getBuildDir().listFiles(new FileFilter() {

                        @Override
                        public boolean accept(File pathname) {
                            return pathname.isDirectory();
                        }
                    });
                    if (subdirs != null) {
                        excludeDirs.addAll(Arrays.asList(subdirs));
                    }
                }
                excludeDirs.removeAll(excl);
                ideaModule.setExcludeDirs(excludeDirs);
                File mainGeneratedSourcesDir = new DslObject(mainSourceSet.getOutput()).getConvention().getPlugin(AptPlugin.AptSourceSetOutputConvention.class).getGeneratedSourcesDir();
                File testGeneratedSourcesDir = new DslObject(testSourceSet.getOutput()).getConvention().getPlugin(AptPlugin.AptSourceSetOutputConvention.class).getGeneratedSourcesDir();
                // For some reason, modifying the existing collections doesn't work.
                // We need to copy the values and then assign it back.
                ideaModule.setSourceDirs(addToSet(ideaModule.getSourceDirs(), mainGeneratedSourcesDir));
                ideaModule.setTestSourceDirs(addToSet(ideaModule.getTestSourceDirs(), testGeneratedSourcesDir));
                ideaModule.setGeneratedSourceDirs(addToSet(ideaModule.getGeneratedSourceDirs(), mainGeneratedSourcesDir, testGeneratedSourcesDir));
            }
            if (apt.isAddCompileOnlyDependencies() || apt.isAddAptDependencies()) {
                final AptPlugin.AptSourceSetConvention mainSourceSetConvention = new DslObject(mainSourceSet).getConvention().getPlugin(AptPlugin.AptSourceSetConvention.class);
                final AptPlugin.AptSourceSetConvention testSourceSetConvention = new DslObject(testSourceSet).getConvention().getPlugin(AptPlugin.AptSourceSetConvention.class);
                final List<Configuration> mainConfigurations = new ArrayList<>();
                final List<Configuration> testConfigurations = new ArrayList<>();
                if (apt.isAddCompileOnlyDependencies()) {
                    mainConfigurations.add(project.getConfigurations().getByName(mainSourceSetConvention.getCompileOnlyConfigurationName()));
                    testConfigurations.add(project.getConfigurations().getByName(testSourceSetConvention.getCompileOnlyConfigurationName()));
                }
                if (apt.isAddAptDependencies()) {
                    mainConfigurations.add(project.getConfigurations().getByName(mainSourceSetConvention.getAnnotationProcessorConfigurationName()));
                    testConfigurations.add(project.getConfigurations().getByName(testSourceSetConvention.getAnnotationProcessorConfigurationName()));
                }
                ideaModule.getScopes().get(apt.getMainDependenciesScope()).get("plus").addAll(mainConfigurations);
                ideaModule.getScopes().get("TEST").get("plus").addAll(testConfigurations);
                project.getTasks().withType(GenerateIdeaModule.class, new Action<GenerateIdeaModule>() {

                    @Override
                    public void execute(GenerateIdeaModule generateIdeaModule) {
                        generateIdeaModule.dependsOn(mainConfigurations.toArray());
                        generateIdeaModule.dependsOn(testConfigurations.toArray());
                    }
                });
            }
        }

        private Set<File> addToSet(Set<File> sourceDirs, File... dirs) {
            Set<File> newSet = new LinkedHashSet<>(sourceDirs);
            newSet.addAll(Arrays.asList(dirs));
            return newSet;
        }
    });
}
Also used : Action(org.gradle.api.Action) SourceSet(org.gradle.api.tasks.SourceSet) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) DslObject(org.gradle.api.internal.plugins.DslObject) IdeaProject(org.gradle.plugins.ide.idea.model.IdeaProject) Project(org.gradle.api.Project) SourceSet(org.gradle.api.tasks.SourceSet) GenerateIdeaModule(org.gradle.plugins.ide.idea.GenerateIdeaModule) IdeaModule(org.gradle.plugins.ide.idea.model.IdeaModule) GenerateIdeaModule(org.gradle.plugins.ide.idea.GenerateIdeaModule) IdeaModel(org.gradle.plugins.ide.idea.model.IdeaModel) NodeList(groovy.util.NodeList) ArrayList(java.util.ArrayList) List(java.util.List) FileFilter(java.io.FileFilter) File(java.io.File)

Aggregations

IdeaModule (org.gradle.plugins.ide.idea.model.IdeaModule)14 File (java.io.File)9 Project (org.gradle.api.Project)6 Set (java.util.Set)5 JavaVersion (org.gradle.api.JavaVersion)5 List (java.util.List)4 Configuration (org.gradle.api.artifacts.Configuration)4 ConventionMapping (org.gradle.api.internal.ConventionMapping)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 SpotlessExtension (com.diffplug.gradle.spotless.SpotlessExtension)2 SpotlessPlugin (com.diffplug.gradle.spotless.SpotlessPlugin)2 VersionsPlugin (com.github.benmanes.gradle.versions.VersionsPlugin)2 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableList.toImmutableList (com.google.common.collect.ImmutableList.toImmutableList)2 Resources (com.google.common.io.Resources)2 Node (groovy.util.Node)2 Map (java.util.Map)2 IConventionAware (org.gradle.api.internal.IConventionAware)2 DslObject (org.gradle.api.internal.plugins.DslObject)2 SourceSet (org.gradle.api.tasks.SourceSet)2