Search in sources :

Example 6 with JavaCompile

use of org.gradle.api.tasks.compile.JavaCompile in project gradle-apt-plugin by tbroyer.

the class AptPlugin method apply.

@Override
public void apply(final Project project) {
    configureCompileTasks(project, JavaCompile.class, new GetCompileOptions<JavaCompile>() {

        @Override
        public CompileOptions getCompileOptions(JavaCompile task) {
            return task.getOptions();
        }
    });
    configureCompileTasks(project, GroovyCompile.class, new GetCompileOptions<GroovyCompile>() {

        @Override
        public CompileOptions getCompileOptions(GroovyCompile task) {
            return task.getOptions();
        }
    });
    project.getPlugins().withType(JavaBasePlugin.class, new Action<JavaBasePlugin>() {

        @Override
        public void execute(JavaBasePlugin javaBasePlugin) {
            final JavaPluginConvention javaConvention = project.getConvention().getPlugin(JavaPluginConvention.class);
            javaConvention.getSourceSets().all(new Action<SourceSet>() {

                @Override
                public void execute(final SourceSet sourceSet) {
                    AptSourceSetConvention convention = IMPL.createAptSourceSetConvention(project, sourceSet);
                    new DslObject(sourceSet).getConvention().getPlugins().put(PLUGIN_ID, convention);
                    AptSourceSetOutputConvention outputConvention = new AptSourceSetOutputConvention(project);
                    outputConvention.setGeneratedSourcesDir(new File(project.getBuildDir(), "generated/source/apt/" + sourceSet.getName()));
                    new DslObject(sourceSet.getOutput()).getConvention().getPlugins().put(PLUGIN_ID, outputConvention);
                    ensureConfigurations(project, sourceSet, convention);
                    configureCompileTaskForSourceSet(project, sourceSet, sourceSet.getCompileJavaTaskName(), JavaCompile.class, new GetCompileOptions<JavaCompile>() {

                        @Override
                        public CompileOptions getCompileOptions(JavaCompile task) {
                            return task.getOptions();
                        }
                    });
                }
            });
        }
    });
    project.getPlugins().withType(GroovyBasePlugin.class, new Action<GroovyBasePlugin>() {

        @Override
        public void execute(GroovyBasePlugin groovyBasePlugin) {
            JavaPluginConvention javaConvention = project.getConvention().getPlugin(JavaPluginConvention.class);
            javaConvention.getSourceSets().all(new Action<SourceSet>() {

                @Override
                public void execute(SourceSet sourceSet) {
                    AptSourceSetConvention convention = new DslObject(sourceSet).getConvention().getPlugin(AptSourceSetConvention.class);
                    configureCompileTaskForSourceSet(project, sourceSet, sourceSet.getCompileTaskName("groovy"), GroovyCompile.class, new GetCompileOptions<GroovyCompile>() {

                        @Override
                        public CompileOptions getCompileOptions(GroovyCompile task) {
                            return task.getOptions();
                        }
                    });
                }
            });
        }
    });
}
Also used : Action(org.gradle.api.Action) DslObject(org.gradle.api.internal.plugins.DslObject) GroovyCompile(org.gradle.api.tasks.compile.GroovyCompile) CompileOptions(org.gradle.api.tasks.compile.CompileOptions) SourceSet(org.gradle.api.tasks.SourceSet) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) GroovyBasePlugin(org.gradle.api.plugins.GroovyBasePlugin) JavaBasePlugin(org.gradle.api.plugins.JavaBasePlugin) JavaCompile(org.gradle.api.tasks.compile.JavaCompile) File(java.io.File)

Example 7 with JavaCompile

use of org.gradle.api.tasks.compile.JavaCompile in project atlas by alibaba.

the class AtlasAppTaskManager method runTask.

@Override
public void runTask() {
    appExtension.getApplicationVariants().forEach(new Consumer<ApplicationVariant>() {

        @Override
        public void accept(ApplicationVariant applicationVariant) {
            AppVariantContext appVariantContext = AtlasBuildContext.sBuilderAdapter.appVariantContextFactory.getAppVariantContext(project, applicationVariant);
            if (!AtlasBuildContext.atlasMainDexHelperMap.containsKey(appVariantContext.getVariantName())) {
                AtlasBuildContext.atlasMainDexHelperMap.put(appVariantContext.getVariantName(), new AtlasMainDexHelper());
            }
            TransformReplacer transformReplacer = new TransformReplacer(appVariantContext);
            repalceAndroidBuilder(applicationVariant);
            List<MtlTaskContext> mtlTaskContextList = new ArrayList<MtlTaskContext>();
            mtlTaskContextList.add(new MtlTaskContext(appVariantContext.getVariantData().preBuildTask));
            mtlTaskContextList.add(new MtlTaskContext(BuildAtlasEnvTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(ScanDupResTask.ConfigActon.class, null));
            mtlTaskContextList.add(new MtlTaskContext(LogDependenciesTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(PrepareAPTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(appVariantContext.getVariantData().mergeAssetsTask));
            mtlTaskContextList.add(new MtlTaskContext(RenderscriptCompile.class));
            mtlTaskContextList.add(new MtlTaskContext(StandardizeLibManifestTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(PrepareBundleInfoTask.ConfigAction.class, null));
            if (!atlasExtension.getTBuildConfig().getClassInject() && atlasExtension.isAtlasEnabled()) {
                mtlTaskContextList.add(new MtlTaskContext(GenerateAtlasSourceTask.ConfigAction.class, null));
            }
            mtlTaskContextList.add(new MtlTaskContext(PreparePackageIdsTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(PrepareAaptTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(AidlCompile.class));
            mtlTaskContextList.add(new MtlTaskContext(GenerateBuildConfig.class));
            mtlTaskContextList.add(new MtlTaskContext(MergeResAwbsConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(MergeAssetAwbsConfigAction.class, null));
            if (null != androidExtension.getDataBinding() && androidExtension.getDataBinding().isEnabled() && !appVariantContext.getAtlasExtension().getTBuildConfig().getAllBundlesToMdex()) {
                // mtlTaskContextList.add(
                // new MtlTaskContext(AwbDataBindingProcessLayoutTask.ConfigAction.class, null));
                mtlTaskContextList.add(new MtlTaskContext(AwbDataBindingExportBuildInfoTask.ConfigAction.class, null));
                mtlTaskContextList.add(new MtlTaskContext(AwbDataBindingMergeArtifactsTask.ConfigAction.class, null));
            }
            mtlTaskContextList.add(new MtlTaskContext(MergeManifests.class));
            mtlTaskContextList.add(new MtlTaskContext(MergeManifestAwbsConfigAction.class, null));
            // mtlTaskContextList.add(new MtlTaskContext(MergeResV4Dir.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(ProcessAndroidResources.class));
            ProcessAndroidResources processAndroidResources = appVariantContext.getScope().getProcessResourcesTask().get(new TaskContainerAdaptor(appVariantContext.getProject().getTasks()));
            if (processAndroidResources.isAapt2Enabled()) {
                processAndroidResources.doLast(new Action<Task>() {

                    @Override
                    public void execute(Task task) {
                        File processResourcePackageOutputDirectory = appVariantContext.getScope().getProcessResourcePackageOutputDirectory();
                        File[] files = processResourcePackageOutputDirectory.listFiles((file, name) -> name.endsWith(SdkConstants.DOT_RES));
                        for (File file : files) {
                            try {
                                ResourcePatch.makePatchable(file);
                            } catch (IOException e) {
                                throw new UncheckedIOException(e);
                            }
                        }
                    }
                });
            }
            mtlTaskContextList.add(new MtlTaskContext(ProcessResAwbsTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(JavacAwbsTask.ConfigAction.class, null));
            if (null != androidExtension.getDataBinding() && androidExtension.getDataBinding().isEnabled() && !appVariantContext.getAtlasExtension().getTBuildConfig().getAllBundlesToMdex()) {
                mtlTaskContextList.add(new MtlTaskContext(AwbDataBindingRenameTask.ConfigAction.class, null));
            }
            mtlTaskContextList.add(new MtlTaskContext(TransformTask.class));
            mtlTaskContextList.add(new MtlTaskContext(PackageAwbsTask.ConfigAction.class, null));
            if (appVariantContext.getAtlasExtension().getTBuildConfig().isIncremental() && (appVariantContext.getBuildType().getPatchConfig() == null || !appVariantContext.getBuildType().getPatchConfig().isCreateTPatch())) {
                // mtlTaskContextList.add(new MtlTaskContext(PrepareBaseApkTask.ConfigAction.class, null));
                final TaskFactory tasks = new TaskContainerAdaptor(project.getTasks());
                VariantScope variantScope = appVariantContext.getVariantData().getScope();
                // create the stream generated from this task
                variantScope.getTransformManager().addStream(OriginalStream.builder(project, applicationVariant.getName()).addContentType(QualifiedContent.DefaultContentType.RESOURCES).addScope(QualifiedContent.Scope.PROJECT).setFolders(new Supplier<Collection<File>>() {

                    @Override
                    public Collection<File> get() {
                        return ImmutableList.of(new File(appVariantContext.apContext.getBaseApk() + "_"));
                    }
                }).build());
            }
            final TaskFactory tasks = new TaskContainerAdaptor(project.getTasks());
            VariantScope variantScope = appVariantContext.getVariantData().getScope();
            mtlTaskContextList.add(new MtlTaskContext(PackageApplication.class));
            if (appVariantContext.getAtlasExtension().isInstantAppEnabled()) {
                mtlTaskContextList.add(new MtlTaskContext(AtlasBundleInstantApp.ConfigAction.class, null));
            }
            mtlTaskContextList.add(new MtlTaskContext(ApBuildTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(DiffBundleInfoTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(TPatchDiffResAPBuildTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(TPatchDiffApkBuildTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext(TPatchTask.ConfigAction.class, null));
            mtlTaskContextList.add(new MtlTaskContext("assemble"));
            new MtlTaskInjector(appVariantContext).injectTasks(mtlTaskContextList, tAndroidBuilder);
            List<MtlTransformContext> mtlTransformContextList = new ArrayList<MtlTransformContext>();
            if (atlasExtension.getTBuildConfig().getClassInject()) {
                mtlTransformContextList.add(new MtlTransformContext(ClassInjectTransform.class, ProGuardTransform.class, DexTransform.class));
            }
            if (variantScope.getInstantRunBuildContext().isInInstantRunMode() && appVariantContext.getVariantConfiguration().getBuildType().isMinifyEnabled()) {
                mtlTransformContextList.add(new MtlTransformContext(DelegateProguardTransform.class, ExtractJarsTransform.class, InstantRunTransform.class));
            }
            if (!mtlTransformContextList.isEmpty()) {
                new MtlTransformInjector(appVariantContext).injectTasks(mtlTransformContextList);
            }
            Collection<BaseVariantOutput> baseVariantOutputDataList = appVariantContext.getVariantOutputData();
            boolean multiDexEnabled = appVariantContext.getVariantData().getVariantConfiguration().isMultiDexEnabled();
            if (atlasExtension.getTBuildConfig().isAtlasMultiDex() && multiDexEnabled) {
                transformReplacer.replaceMultiDexListTransform();
            }
            transformReplacer.replaceProguardTransform();
            transformReplacer.disableCache();
            if (variantScope.getGlobalScope().getExtension().getDataBinding().isEnabled() && !appVariantContext.getAtlasExtension().getTBuildConfig().getAllBundlesToMdex()) {
                transformReplacer.replaceDataBindingMergeArtifactsTransform();
            }
            for (final BaseVariantOutput vod : baseVariantOutputDataList) {
                transformReplacer.replaceFixStackFramesTransform(vod);
                transformReplacer.replaceDesugarTransform(vod);
                transformReplacer.replaceDexArchiveBuilderTransform(vod);
                transformReplacer.replaceDexExternalLibMerge(vod);
                transformReplacer.replaceDexMerge(vod);
                transformReplacer.replaceDexTransform(appVariantContext, vod);
                transformReplacer.replaceShrinkResourcesTransform();
                transformReplacer.replaceMergeJavaResourcesTransform(appVariantContext, vod);
                transformReplacer.repalaceSomeInstantTransform(vod);
                if (atlasExtension.getTBuildConfig().isIncremental()) {
                    InstantRunPatchingPolicy patchingPolicy = variantScope.getInstantRunBuildContext().getPatchingPolicy();
                    BaseVariantOutputImpl variantOutput = (BaseVariantOutputImpl) vod;
                    ApkData data = ApkDataUtils.get(variantOutput);
                    AtlasDependencyTree atlasDependencyTree = AtlasBuildContext.androidDependencyTrees.get(variantScope.getFullVariantName());
                // 
                }
            }
            // Boolean includeCompileClasspath =
            // appVariantContext.getScope().getVariantConfiguration()
            // .getJavaCompileOptions()
            // .getAnnotationProcessorOptions()
            // .getIncludeCompileClasspath();
            // appVariantContext.getVariantData().javaCompilerTask.doFirst(task -> {
            // JavaCompile compile = (JavaCompile) task;
            // Set<File> mainDexFiles = new MainFilesCollection(appVariantContext.getVariantName()).getFiles();
            // FileCollection mainFiles = appVariantContext.getProject().files(mainDexFiles);
            // FileCollection files = appVariantContext.getScope().getArtifactFileCollection(ANNOTATION_PROCESSOR, ALL, JAR);
            // FileCollection bootFiles = appVariantContext.getProject().files(appVariantContext.getScope().getGlobalScope().getAndroidBuilder().getBootClasspath(false));
            // mainFiles = mainFiles.plus(bootFiles);
            // FileCollection fileCollection = compile.getClasspath();
            // File kotlinClasses = null;
            // for (File file : fileCollection) {
            // if (file.getAbsolutePath().contains("kotlin-classes")) {
            // mainFiles = mainFiles.plus(appVariantContext.getProject().files(file));
            // kotlinClasses = file;
            // break;
            // }
            // }
            // compile.setClasspath(mainFiles);
            // if (Boolean.TRUE.equals(includeCompileClasspath)) {
            // compile.getOptions().setAnnotationProcessorPath(files.plus(mainFiles));
            // }
            // });
            appVariantContext.getVariantData().javaCompilerTask.doLast(new Action<Task>() {

                @Override
                public void execute(Task task) {
                    JavaCompile compile = (JavaCompile) task;
                    AtlasBuildContext.atlasMainDexHelperMap.get(appVariantContext.getVariantName()).getInputDirs().add(compile.getDestinationDir());
                }
            });
            PackageAndroidArtifact packageAndroidArtifact = appVariantContext.getVariantData().getTaskByType(PackageAndroidArtifact.class);
            if (packageAndroidArtifact != null) {
                ReflectUtils.updateField(packageAndroidArtifact, "javaResourceFiles", new AbstractFileCollection() {

                    @Override
                    public String getDisplayName() {
                        return "java-merge-res.jar";
                    }

                    @Override
                    public Set<File> getFiles() {
                        if (AtlasBuildContext.atlasMainDexHelperMap.get(packageAndroidArtifact.getVariantName()).getMainJavaRes() == null) {
                            return Sets.newHashSet();
                        }
                        return Sets.newHashSet(AtlasBuildContext.atlasMainDexHelperMap.get(packageAndroidArtifact.getVariantName()).getMainJavaRes());
                    }
                });
            }
            TaskCollection<ExtractTryWithResourcesSupportJar> taskCollection = appVariantContext.getProject().getTasks().withType(ExtractTryWithResourcesSupportJar.class);
            for (ExtractTryWithResourcesSupportJar task : taskCollection) {
                task.doLast(new Action<Task>() {

                    @Override
                    public void execute(Task task) {
                        ConfigurableFileCollection fileCollection = variantScope.getTryWithResourceRuntimeSupportJar();
                        for (File file : fileCollection.getFiles()) {
                            if (file.exists()) {
                                AtlasBuildContext.atlasMainDexHelperMap.get(variantScope.getFullVariantName()).addMainDex(new BuildAtlasEnvTask.FileIdentity("runtime-deps-try-with-resources", file, false, false));
                                break;
                            }
                        }
                    }
                });
            }
        }
    });
}
Also used : TPatchDiffApkBuildTask(com.taobao.android.builder.tasks.tpatch.TPatchDiffApkBuildTask) AwbDataBindingMergeArtifactsTask(com.taobao.android.builder.tasks.app.databinding.AwbDataBindingMergeArtifactsTask) AwbDataBindingExportBuildInfoTask(com.taobao.android.builder.tasks.app.databinding.AwbDataBindingExportBuildInfoTask) PackageAwbsTask(com.taobao.android.builder.tasks.app.bundle.PackageAwbsTask) TransformTask(com.android.build.gradle.internal.pipeline.TransformTask) AwbDataBindingRenameTask(com.taobao.android.builder.tasks.app.databinding.AwbDataBindingRenameTask) PrepareAPTask(com.taobao.android.builder.tasks.PrepareAPTask) TPatchDiffResAPBuildTask(com.taobao.android.builder.tasks.tpatch.TPatchDiffResAPBuildTask) ProcessResAwbsTask(com.taobao.android.builder.tasks.app.bundle.ProcessResAwbsTask) TPatchTask(com.taobao.android.builder.tasks.tpatch.TPatchTask) BuildAtlasEnvTask(com.taobao.android.builder.tasks.app.BuildAtlasEnvTask) AbstractTask(org.gradle.api.internal.AbstractTask) PreparePackageIdsTask(com.taobao.android.builder.tasks.app.prepare.PreparePackageIdsTask) PrepareAaptTask(com.taobao.android.builder.tasks.app.prepare.PrepareAaptTask) Task(org.gradle.api.Task) JavacAwbsTask(com.taobao.android.builder.tasks.app.bundle.JavacAwbsTask) StandardizeLibManifestTask(com.taobao.android.builder.tasks.app.manifest.StandardizeLibManifestTask) PrepareBundleInfoTask(com.taobao.android.builder.tasks.app.prepare.PrepareBundleInfoTask) DiffBundleInfoTask(com.taobao.android.builder.tasks.tpatch.DiffBundleInfoTask) AwbDataBindingExportBuildInfoTask(com.taobao.android.builder.tasks.app.databinding.AwbDataBindingExportBuildInfoTask) ApplicationVariant(com.android.build.gradle.api.ApplicationVariant) TPatchTask(com.taobao.android.builder.tasks.tpatch.TPatchTask) ConfigurableFileCollection(org.gradle.api.file.ConfigurableFileCollection) UncheckedIOException(java.io.UncheckedIOException) ExtractTryWithResourcesSupportJar(com.android.build.gradle.internal.tasks.ExtractTryWithResourcesSupportJar) BaseVariantOutput(com.android.build.gradle.api.BaseVariantOutput) StandardizeLibManifestTask(com.taobao.android.builder.tasks.app.manifest.StandardizeLibManifestTask) MtlTaskContext(com.taobao.android.builder.tasks.manager.MtlTaskContext) PrepareAPTask(com.taobao.android.builder.tasks.PrepareAPTask) ImmutableList(com.google.common.collect.ImmutableList) TPatchDiffResAPBuildTask(com.taobao.android.builder.tasks.tpatch.TPatchDiffResAPBuildTask) BuildAtlasEnvTask(com.taobao.android.builder.tasks.app.BuildAtlasEnvTask) MtlTransformContext(com.taobao.android.builder.tasks.manager.transform.MtlTransformContext) AtlasMainDexHelper(com.taobao.android.builder.AtlasMainDexHelper) InstantRunPatchingPolicy(com.android.build.gradle.internal.incremental.InstantRunPatchingPolicy) AbstractFileCollection(org.gradle.api.internal.file.AbstractFileCollection) TaskCollection(org.gradle.api.tasks.TaskCollection) AbstractFileCollection(org.gradle.api.internal.file.AbstractFileCollection) ConfigurableFileCollection(org.gradle.api.file.ConfigurableFileCollection) FileCollection(org.gradle.api.file.FileCollection) AwbDataBindingRenameTask(com.taobao.android.builder.tasks.app.databinding.AwbDataBindingRenameTask) File(java.io.File) JavaCompile(org.gradle.api.tasks.compile.JavaCompile) Action(org.gradle.api.Action) PrepareBundleInfoTask(com.taobao.android.builder.tasks.app.prepare.PrepareBundleInfoTask) AwbDataBindingMergeArtifactsTask(com.taobao.android.builder.tasks.app.databinding.AwbDataBindingMergeArtifactsTask) TaskContainerAdaptor(com.android.build.gradle.internal.TaskContainerAdaptor) TPatchDiffApkBuildTask(com.taobao.android.builder.tasks.tpatch.TPatchDiffApkBuildTask) MtlTransformInjector(com.taobao.android.builder.tasks.manager.transform.MtlTransformInjector) TransformReplacer(com.taobao.android.builder.tasks.transform.TransformReplacer) PackageAwbsTask(com.taobao.android.builder.tasks.app.bundle.PackageAwbsTask) DiffBundleInfoTask(com.taobao.android.builder.tasks.tpatch.DiffBundleInfoTask) Supplier(com.google.common.base.Supplier) ApkData(com.android.ide.common.build.ApkData) JavacAwbsTask(com.taobao.android.builder.tasks.app.bundle.JavacAwbsTask) VariantScope(com.android.build.gradle.internal.scope.VariantScope) BaseVariantOutputImpl(com.android.build.gradle.internal.api.BaseVariantOutputImpl) AtlasBundleInstantApp(com.taobao.android.builder.tasks.instantapp.AtlasBundleInstantApp) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) MtlTaskInjector(com.taobao.android.builder.tasks.manager.MtlTaskInjector) AtlasDependencyTree(com.taobao.android.builder.dependency.AtlasDependencyTree) TaskCollection(org.gradle.api.tasks.TaskCollection) TaskFactory(com.android.build.gradle.internal.TaskFactory) PreparePackageIdsTask(com.taobao.android.builder.tasks.app.prepare.PreparePackageIdsTask) PrepareAaptTask(com.taobao.android.builder.tasks.app.prepare.PrepareAaptTask) ProcessResAwbsTask(com.taobao.android.builder.tasks.app.bundle.ProcessResAwbsTask) AppVariantContext(com.android.build.gradle.internal.api.AppVariantContext)

Example 8 with JavaCompile

use of org.gradle.api.tasks.compile.JavaCompile in project spring-boot by spring-projects.

the class ConfigurationPropertiesPlugin method configureAdditionalMetadataLocationsCompilerArgument.

private void configureAdditionalMetadataLocationsCompilerArgument(Project project) {
    JavaCompile compileJava = project.getTasks().withType(JavaCompile.class).getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME);
    ((Task) compileJava).getInputs().files(project.getTasks().getByName(JavaPlugin.PROCESS_RESOURCES_TASK_NAME)).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName("processed resources");
    SourceSet mainSourceSet = project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME);
    compileJava.getOptions().getCompilerArgs().add("-Aorg.springframework.boot.configurationprocessor.additionalMetadataLocations=" + StringUtils.collectionToCommaDelimitedString(mainSourceSet.getResources().getSourceDirectories().getFiles().stream().map(project.getRootProject()::relativePath).collect(Collectors.toSet())));
}
Also used : SourceSet(org.gradle.api.tasks.SourceSet) JavaCompile(org.gradle.api.tasks.compile.JavaCompile)

Example 9 with JavaCompile

use of org.gradle.api.tasks.compile.JavaCompile in project rest.li by linkedin.

the class PegasusPlugin method configureRestClientGeneration.

// Generate rest client from idl files generated from java source files in the specified source set.
// 
// This generates rest client source files from idl file generated from java source files
// in the source set. The generated rest client source files will be in a new source set.
// It also compiles the rest client source files into classes, and creates both the
// rest model and rest client jar files.
// 
@SuppressWarnings("deprecation")
protected void configureRestClientGeneration(Project project, SourceSet sourceSet) {
    // idl directory for api project
    File idlDir = project.file(getIdlPath(project, sourceSet));
    if (SharedFileUtils.getSuffixedFiles(project, idlDir, IDL_FILE_SUFFIX).isEmpty()) {
        return;
    }
    File generatedRestClientDir = project.file(getGeneratedDirPath(project, sourceSet, REST_GEN_TYPE) + File.separatorChar + "java");
    // always include imported data template jars in compileClasspath of rest client
    FileCollection dataModelConfig = getDataModelConfig(project, sourceSet);
    // if data templates generated from this source set, add the generated data template jar to compileClasspath
    // of rest client.
    String dataTemplateSourceSetName = getGeneratedSourceSetName(sourceSet, DATA_TEMPLATE_GEN_TYPE);
    Jar dataTemplateJarTask = null;
    SourceSetContainer sourceSets = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets();
    FileCollection dataModels;
    if (sourceSets.findByName(dataTemplateSourceSetName) != null) {
        if (debug) {
            System.out.println("sourceSet " + sourceSet.getName() + " has generated sourceSet " + dataTemplateSourceSetName);
        }
        dataTemplateJarTask = (Jar) project.getTasks().getByName(sourceSet.getName() + "DataTemplateJar");
        // FIXME change to #getArchiveFile(); breaks backwards-compatibility before 5.1
        dataModels = dataModelConfig.plus(project.files(dataTemplateJarTask.getArchivePath()));
    } else {
        dataModels = dataModelConfig;
    }
    // create source set for generated rest model, rest client source and class files.
    String targetSourceSetName = getGeneratedSourceSetName(sourceSet, REST_GEN_TYPE);
    SourceSet targetSourceSet = sourceSets.create(targetSourceSetName, ss -> {
        ss.java(sourceDirectorySet -> sourceDirectorySet.srcDir(generatedRestClientDir));
        ss.setCompileClasspath(dataModels.plus(project.getConfigurations().getByName("restClientCompile")));
    });
    project.getPlugins().withType(EclipsePlugin.class, eclipsePlugin -> {
        EclipseModel eclipseModel = (EclipseModel) project.getExtensions().findByName("eclipse");
        eclipseModel.getClasspath().getPlusConfigurations().add(project.getConfigurations().getByName("restClientCompile"));
    });
    // idea plugin needs to know about new rest client source directory and its dependencies
    addGeneratedDir(project, targetSourceSet, Arrays.asList(getDataModelConfig(project, sourceSet), project.getConfigurations().getByName("restClientCompile")));
    // generate the rest client source files
    GenerateRestClientTask generateRestClientTask = project.getTasks().create(targetSourceSet.getTaskName("generate", "restClient"), GenerateRestClientTask.class, task -> {
        task.dependsOn(project.getConfigurations().getByName("dataTemplate"));
        task.setInputDir(idlDir);
        task.setResolverPath(dataModels.plus(project.getConfigurations().getByName("restClientCompile")));
        task.setRuntimeClasspath(project.getConfigurations().getByName("dataModel").plus(project.getConfigurations().getByName("dataTemplate").getArtifacts().getFiles()));
        task.setCodegenClasspath(project.getConfigurations().getByName(PEGASUS_PLUGIN_CONFIGURATION));
        task.setDestinationDir(generatedRestClientDir);
        task.setRestli2FormatSuppressed(project.hasProperty(SUPPRESS_REST_CLIENT_RESTLI_2));
        task.setRestli1FormatSuppressed(project.hasProperty(SUPPRESS_REST_CLIENT_RESTLI_1));
        if (isPropertyTrue(project, ENABLE_ARG_FILE)) {
            task.setEnableArgFile(true);
        }
        if (isPropertyTrue(project, CODE_GEN_PATH_CASE_SENSITIVE)) {
            task.setGenerateLowercasePath(false);
        }
        if (isPropertyTrue(project, ENABLE_FLUENT_API)) {
            task.setGenerateFluentApi(true);
        }
        task.doFirst(new CacheableAction<>(t -> project.delete(generatedRestClientDir)));
    });
    if (dataTemplateJarTask != null) {
        generateRestClientTask.dependsOn(dataTemplateJarTask);
    }
    // TODO: Tighten the types so that _generateSourcesJarTask must be of type Jar.
    ((Jar) _generateSourcesJarTask).from(generateRestClientTask.getDestinationDir());
    _generateSourcesJarTask.dependsOn(generateRestClientTask);
    _generateJavadocTask.source(generateRestClientTask.getDestinationDir());
    _generateJavadocTask.setClasspath(_generateJavadocTask.getClasspath().plus(project.getConfigurations().getByName("restClientCompile")).plus(generateRestClientTask.getResolverPath()));
    _generateJavadocTask.dependsOn(generateRestClientTask);
    // make sure rest client source files have been generated before compiling them
    JavaCompile compileGeneratedRestClientTask = (JavaCompile) project.getTasks().getByName(targetSourceSet.getCompileJavaTaskName());
    compileGeneratedRestClientTask.dependsOn(generateRestClientTask);
    compileGeneratedRestClientTask.getOptions().getCompilerArgs().add("-Xlint:-deprecation");
    // create the rest model jar file
    Task restModelJarTask = project.getTasks().create(sourceSet.getName() + "RestModelJar", Jar.class, task -> {
        task.from(idlDir, copySpec -> {
            copySpec.eachFile(fileCopyDetails -> project.getLogger().info("Add idl file: {}", fileCopyDetails));
            copySpec.setIncludes(Collections.singletonList('*' + IDL_FILE_SUFFIX));
        });
        // FIXME change to #getArchiveAppendix().set(...); breaks backwards-compatibility before 5.1
        task.setAppendix(getAppendix(sourceSet, "rest-model"));
        task.setDescription("Generate rest model jar");
    });
    // create the rest client jar file
    Task restClientJarTask = project.getTasks().create(sourceSet.getName() + "RestClientJar", Jar.class, task -> {
        task.dependsOn(compileGeneratedRestClientTask);
        task.from(idlDir, copySpec -> {
            copySpec.eachFile(fileCopyDetails -> {
                project.getLogger().info("Add interface file: {}", fileCopyDetails);
                fileCopyDetails.setPath("idl" + File.separatorChar + fileCopyDetails.getPath());
            });
            copySpec.setIncludes(Collections.singletonList('*' + IDL_FILE_SUFFIX));
        });
        task.from(targetSourceSet.getOutput());
        // FIXME change to #getArchiveAppendix().set(...); breaks backwards-compatibility before 5.1
        task.setAppendix(getAppendix(sourceSet, "rest-client"));
        task.setDescription("Generate rest client jar");
    });
    // add the rest model jar and the rest client jar to the list of project artifacts.
    if (!isTestSourceSet(sourceSet)) {
        project.getArtifacts().add("restModel", restModelJarTask);
        project.getArtifacts().add("restClient", restClientJarTask);
    } else {
        project.getArtifacts().add("testRestModel", restModelJarTask);
        project.getArtifacts().add("testRestClient", restClientJarTask);
    }
}
Also used : CompatibilityLogChecker(com.linkedin.pegasus.gradle.internal.CompatibilityLogChecker) Arrays(java.util.Arrays) PublishRestModelTask(com.linkedin.pegasus.gradle.tasks.PublishRestModelTask) ValidateExtensionSchemaTask(com.linkedin.pegasus.gradle.tasks.ValidateExtensionSchemaTask) JavaPlugin(org.gradle.api.plugins.JavaPlugin) IdeaPlugin(org.gradle.plugins.ide.idea.IdeaPlugin) CheckSnapshotTask(com.linkedin.pegasus.gradle.tasks.CheckSnapshotTask) EclipsePlugin(org.gradle.plugins.ide.eclipse.EclipsePlugin) Task(org.gradle.api.Task) PublishingExtension(org.gradle.api.publish.PublishingExtension) Javadoc(org.gradle.api.tasks.javadoc.Javadoc) JavaBasePlugin(org.gradle.api.plugins.JavaBasePlugin) ConfigurationContainer(org.gradle.api.artifacts.ConfigurationContainer) TaskProvider(org.gradle.api.tasks.TaskProvider) Locale(java.util.Locale) Map(java.util.Map) TranslateSchemasTask(com.linkedin.pegasus.gradle.tasks.TranslateSchemasTask) CheckPegasusSnapshotTask(com.linkedin.pegasus.gradle.tasks.CheckPegasusSnapshotTask) Method(java.lang.reflect.Method) Path(java.nio.file.Path) GradleVersion(org.gradle.util.GradleVersion) IdeaModule(org.gradle.plugins.ide.idea.model.IdeaModule) Delete(org.gradle.api.tasks.Delete) Project(org.gradle.api.Project) Collection(java.util.Collection) ChangedFileReportTask(com.linkedin.pegasus.gradle.tasks.ChangedFileReportTask) Set(java.util.Set) IvyPublishPlugin(org.gradle.api.publish.ivy.plugins.IvyPublishPlugin) GeneratePegasusSnapshotTask(com.linkedin.pegasus.gradle.tasks.GeneratePegasusSnapshotTask) Collectors(java.util.stream.Collectors) IvyPublication(org.gradle.api.publish.ivy.IvyPublication) List(java.util.List) IdlOptions(com.linkedin.pegasus.gradle.PegasusOptions.IdlOptions) JavaPluginExtension(org.gradle.api.plugins.JavaPluginExtension) Pattern(java.util.regex.Pattern) ProcessResources(org.gradle.language.jvm.tasks.ProcessResources) GenerateRestClientTask(com.linkedin.pegasus.gradle.tasks.GenerateRestClientTask) GenerateRestModelTask(com.linkedin.pegasus.gradle.tasks.GenerateRestModelTask) HashMap(java.util.HashMap) Function(java.util.function.Function) FileCollection(org.gradle.api.file.FileCollection) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) SourceSet(org.gradle.api.tasks.SourceSet) HashSet(java.util.HashSet) Configuration(org.gradle.api.artifacts.Configuration) LifecycleBasePlugin(org.gradle.language.base.plugins.LifecycleBasePlugin) Sync(org.gradle.api.tasks.Sync) SourceSetContainer(org.gradle.api.tasks.SourceSetContainer) CheckRestModelTask(com.linkedin.pegasus.gradle.tasks.CheckRestModelTask) JavaCompile(org.gradle.api.tasks.compile.JavaCompile) Properties(java.util.Properties) Jar(org.gradle.api.tasks.bundling.Jar) Action(org.gradle.api.Action) Files(java.nio.file.Files) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) ValidateSchemaAnnotationTask(com.linkedin.pegasus.gradle.tasks.ValidateSchemaAnnotationTask) IOException(java.io.IOException) EclipseModel(org.gradle.plugins.ide.eclipse.model.EclipseModel) File(java.io.File) CheckIdlTask(com.linkedin.pegasus.gradle.tasks.CheckIdlTask) GenerateDataTemplateTask(com.linkedin.pegasus.gradle.tasks.GenerateDataTemplateTask) GenerateAvroSchemaTask(com.linkedin.pegasus.gradle.tasks.GenerateAvroSchemaTask) GradleException(org.gradle.api.GradleException) Collections(java.util.Collections) Plugin(org.gradle.api.Plugin) Copy(org.gradle.api.tasks.Copy) InputStream(java.io.InputStream) PublishRestModelTask(com.linkedin.pegasus.gradle.tasks.PublishRestModelTask) ValidateExtensionSchemaTask(com.linkedin.pegasus.gradle.tasks.ValidateExtensionSchemaTask) CheckSnapshotTask(com.linkedin.pegasus.gradle.tasks.CheckSnapshotTask) Task(org.gradle.api.Task) TranslateSchemasTask(com.linkedin.pegasus.gradle.tasks.TranslateSchemasTask) CheckPegasusSnapshotTask(com.linkedin.pegasus.gradle.tasks.CheckPegasusSnapshotTask) ChangedFileReportTask(com.linkedin.pegasus.gradle.tasks.ChangedFileReportTask) GeneratePegasusSnapshotTask(com.linkedin.pegasus.gradle.tasks.GeneratePegasusSnapshotTask) GenerateRestClientTask(com.linkedin.pegasus.gradle.tasks.GenerateRestClientTask) GenerateRestModelTask(com.linkedin.pegasus.gradle.tasks.GenerateRestModelTask) CheckRestModelTask(com.linkedin.pegasus.gradle.tasks.CheckRestModelTask) ValidateSchemaAnnotationTask(com.linkedin.pegasus.gradle.tasks.ValidateSchemaAnnotationTask) CheckIdlTask(com.linkedin.pegasus.gradle.tasks.CheckIdlTask) GenerateDataTemplateTask(com.linkedin.pegasus.gradle.tasks.GenerateDataTemplateTask) GenerateAvroSchemaTask(com.linkedin.pegasus.gradle.tasks.GenerateAvroSchemaTask) FileCollection(org.gradle.api.file.FileCollection) SourceSetContainer(org.gradle.api.tasks.SourceSetContainer) SourceSet(org.gradle.api.tasks.SourceSet) JavaPluginConvention(org.gradle.api.plugins.JavaPluginConvention) EclipseModel(org.gradle.plugins.ide.eclipse.model.EclipseModel) GenerateRestClientTask(com.linkedin.pegasus.gradle.tasks.GenerateRestClientTask) Jar(org.gradle.api.tasks.bundling.Jar) File(java.io.File) JavaCompile(org.gradle.api.tasks.compile.JavaCompile)

Example 10 with JavaCompile

use of org.gradle.api.tasks.compile.JavaCompile in project gradle by gradle.

the class EclipseClasspath method resolveDependencies.

/**
 * Calculates, resolves and returns dependency entries of this classpath.
 */
public List<ClasspathEntry> resolveDependencies() {
    ProjectInternal projectInternal = (ProjectInternal) this.project;
    IdeArtifactRegistry ideArtifactRegistry = projectInternal.getServices().get(IdeArtifactRegistry.class);
    boolean inferModulePath = false;
    Task javaCompileTask = project.getTasks().findByName(JavaPlugin.COMPILE_JAVA_TASK_NAME);
    if (javaCompileTask instanceof JavaCompile) {
        JavaCompile javaCompile = (JavaCompile) javaCompileTask;
        inferModulePath = javaCompile.getModularity().getInferModulePath().get();
        if (inferModulePath) {
            List<File> sourceRoots = CompilationSourceDirs.inferSourceRoots((FileTreeInternal) javaCompile.getSource());
            inferModulePath = JavaModuleDetector.isModuleSource(true, sourceRoots);
        }
    }
    ClasspathFactory classpathFactory = new ClasspathFactory(this, ideArtifactRegistry, new DefaultGradleApiSourcesResolver(projectInternal.newDetachedResolver()), inferModulePath);
    return classpathFactory.createEntries();
}
Also used : Task(org.gradle.api.Task) ProjectInternal(org.gradle.api.internal.project.ProjectInternal) IdeArtifactRegistry(org.gradle.plugins.ide.internal.IdeArtifactRegistry) JavaCompile(org.gradle.api.tasks.compile.JavaCompile) File(java.io.File) DefaultGradleApiSourcesResolver(org.gradle.plugins.ide.internal.resolver.DefaultGradleApiSourcesResolver) ClasspathFactory(org.gradle.plugins.ide.eclipse.model.internal.ClasspathFactory)

Aggregations

JavaCompile (org.gradle.api.tasks.compile.JavaCompile)17 File (java.io.File)10 SourceSet (org.gradle.api.tasks.SourceSet)7 Task (org.gradle.api.Task)6 Configuration (org.gradle.api.artifacts.Configuration)6 Action (org.gradle.api.Action)5 FileCollection (org.gradle.api.file.FileCollection)5 Jar (org.gradle.api.tasks.bundling.Jar)5 SourceSetContainer (org.gradle.api.tasks.SourceSetContainer)4 ConfigurationContainer (org.gradle.api.artifacts.ConfigurationContainer)3 IdlOptions (com.linkedin.pegasus.gradle.PegasusOptions.IdlOptions)2 CompatibilityLogChecker (com.linkedin.pegasus.gradle.internal.CompatibilityLogChecker)2 ChangedFileReportTask (com.linkedin.pegasus.gradle.tasks.ChangedFileReportTask)2 CheckIdlTask (com.linkedin.pegasus.gradle.tasks.CheckIdlTask)2 CheckPegasusSnapshotTask (com.linkedin.pegasus.gradle.tasks.CheckPegasusSnapshotTask)2 CheckRestModelTask (com.linkedin.pegasus.gradle.tasks.CheckRestModelTask)2 CheckSnapshotTask (com.linkedin.pegasus.gradle.tasks.CheckSnapshotTask)2 GenerateAvroSchemaTask (com.linkedin.pegasus.gradle.tasks.GenerateAvroSchemaTask)2 GenerateDataTemplateTask (com.linkedin.pegasus.gradle.tasks.GenerateDataTemplateTask)2 GeneratePegasusSnapshotTask (com.linkedin.pegasus.gradle.tasks.GeneratePegasusSnapshotTask)2