Search in sources :

Example 11 with CommandLineArgumentProvider

use of org.gradle.process.CommandLineArgumentProvider in project micronaut-gradle-plugin by micronaut-projects.

the class MicronautGraalPlugin method registerTestAgainstNativeImageTask.

/**
 * For each `Test` task, we register a new `testNativeImage` task which tests _against_ the native image
 * server. Note that this is different from the `nativeTest` task that the GraalVM Gradle plugin provides,
 * as the latter executes all tests _within_ the native image.
 */
private void registerTestAgainstNativeImageTask(Set<String> alreadyRegistered, TaskContainer tasks, String testName) {
    if (alreadyRegistered.add(testName)) {
        tasks.register(testName + "NativeImage", Test.class, nativeImageTestTask -> {
            Test testTask = (Test) tasks.getByName(testName);
            nativeImageTestTask.setClasspath(testTask.getClasspath());
            nativeImageTestTask.getJavaLauncher().set(testTask.getJavaLauncher());
            BuildNativeImageTask nativeBuild = (BuildNativeImageTask) tasks.findByName("nativeCompile");
            nativeImageTestTask.setForkEvery(testTask.getForkEvery());
            nativeImageTestTask.setTestClassesDirs(testTask.getTestClassesDirs());
            nativeImageTestTask.getJvmArgumentProviders().add(new CommandLineArgumentProvider() {

                @InputFile
                @PathSensitive(PathSensitivity.RELATIVE)
                Provider<RegularFile> getInputFile() {
                    return nativeBuild.getOutputFile();
                }

                @Override
                public Iterable<String> asArguments() {
                    return Collections.singleton("-Dmicronaut.test.server.executable=" + getInputFile().get().getAsFile().getAbsolutePath());
                }
            });
            nativeImageTestTask.setDescription("Runs tests against a native image build of the server. Requires the server to allow the port to configurable with 'micronaut.server.port'.");
        });
    }
}
Also used : BuildNativeImageTask(org.graalvm.buildtools.gradle.tasks.BuildNativeImageTask) CommandLineArgumentProvider(org.gradle.process.CommandLineArgumentProvider) Test(org.gradle.api.tasks.testing.Test) PathSensitive(org.gradle.api.tasks.PathSensitive) InputFile(org.gradle.api.tasks.InputFile) CommandLineArgumentProvider(org.gradle.process.CommandLineArgumentProvider) Provider(org.gradle.api.provider.Provider)

Example 12 with CommandLineArgumentProvider

use of org.gradle.process.CommandLineArgumentProvider in project gradle-native by nokeedev.

the class JniLibraryPlugin method configureJavaJniRuntime.

private void configureJavaJniRuntime(Project project, JavaNativeInterfaceLibrary library) {
    project.getTasks().named("test", Test.class, task -> {
        task.dependsOn((Callable<Iterable<File>>) () -> {
            val variant = library.getDevelopmentVariant().getOrNull();
            if (variant == null) {
                return emptyList();
            }
            return variant.getNativeRuntimeFiles();
        });
        // TODO: notify when no native library exists
        task.getJvmArgumentProviders().add(new CommandLineArgumentProvider() {

            @Override
            public Iterable<String> asArguments() {
                String path = library.getVariants().get().stream().sorted(preferHostOperatingSystemFamily().thenComparing(preferHostMachineArchitecture())).filter(it -> it.getSharedLibrary().isBuildable()).map(JniLibrary::getNativeRuntimeFiles).flatMap(it -> it.getFiles().stream()).map(it -> it.getParentFile().getAbsolutePath()).collect(joining(File.pathSeparator));
                return ImmutableList.of("-Djava.library.path=" + path);
            }
        });
    });
}
Also used : lombok.val(lombok.val) ObjectiveCppLanguagePlugin(dev.nokee.language.objectivecpp.internal.plugins.ObjectiveCppLanguagePlugin) CLanguagePlugin(dev.nokee.language.c.internal.plugins.CLanguagePlugin) ModelRegistry(dev.nokee.model.internal.registry.ModelRegistry) NativeComponentBasePlugin.finalizeModelNodeOf(dev.nokee.platform.nativebase.internal.plugins.NativeComponentBasePlugin.finalizeModelNodeOf) NativeBasePlugin(org.gradle.language.plugins.NativeBasePlugin) CURRENT_MODEL_PLUGIN_IDS(dev.nokee.platform.jni.internal.plugins.JniLibraryPlugin.IncompatiblePluginsAdvice.CURRENT_MODEL_PLUGIN_IDS) ConfigurationContainer(org.gradle.api.artifacts.ConfigurationContainer) ModelNodes(dev.nokee.model.internal.core.ModelNodes) ImmutableSet(com.google.common.collect.ImmutableSet) Project(org.gradle.api.Project) Collections.emptyList(java.util.Collections.emptyList) ComponentIdentifier(dev.nokee.platform.base.internal.ComponentIdentifier) NativeVariantComparators.preferHostMachineArchitecture(dev.nokee.platform.nativebase.internal.NativeVariantComparators.preferHostMachineArchitecture) Set(java.util.Set) Collectors.joining(java.util.stream.Collectors.joining) IncompatiblePluginUsage(dev.nokee.platform.jni.internal.IncompatiblePluginUsage) Objects(java.util.Objects) JavaNativeInterfaceLibraryComponentRegistrationFactory(dev.nokee.platform.jni.internal.JavaNativeInterfaceLibraryComponentRegistrationFactory) TaskContainer(org.gradle.api.tasks.TaskContainer) ToolChainSelectorInternal(dev.nokee.language.nativebase.internal.ToolChainSelectorInternal) Optional(java.util.Optional) SOFTWARE_MODEL_PLUGIN_IDS(dev.nokee.platform.jni.internal.plugins.JniLibraryPlugin.IncompatiblePluginsAdvice.SOFTWARE_MODEL_PLUGIN_IDS) ModelProperties(dev.nokee.model.internal.core.ModelProperties) Getter(lombok.Getter) Callable(java.util.concurrent.Callable) JAVA_APPLICATION_PLUGIN_ID(dev.nokee.platform.jni.internal.plugins.JniLibraryPlugin.IncompatiblePluginsAdvice.JAVA_APPLICATION_PLUGIN_ID) CommandLineArgumentProvider(org.gradle.process.CommandLineArgumentProvider) ProjectIdentifier(dev.nokee.model.internal.ProjectIdentifier) Inject(javax.inject.Inject) ObjectiveCLanguagePlugin(dev.nokee.language.objectivec.internal.plugins.ObjectiveCLanguagePlugin) VariantView(dev.nokee.platform.base.VariantView) AccessLevel(lombok.AccessLevel) ImmutableList(com.google.common.collect.ImmutableList) DependencyHandler(org.gradle.api.artifacts.dsl.DependencyHandler) DarwinFrameworkResolutionSupportPlugin(dev.nokee.runtime.darwin.internal.plugins.DarwinFrameworkResolutionSupportPlugin) JAVA_LIBRARY_PLUGIN_ID(dev.nokee.platform.jni.internal.plugins.JniLibraryPlugin.IncompatiblePluginsAdvice.JAVA_LIBRARY_PLUGIN_ID) Test(org.gradle.api.tasks.testing.Test) Nullable(javax.annotation.Nullable) BaseVariant(dev.nokee.platform.base.internal.BaseVariant) JniLibrary(dev.nokee.platform.jni.JniLibrary) NativeRuntimePlugin(dev.nokee.runtime.nativebase.internal.NativeRuntimePlugin) lombok.val(lombok.val) NativeVariantComparators.preferHostOperatingSystemFamily(dev.nokee.platform.nativebase.internal.NativeVariantComparators.preferHostOperatingSystemFamily) File(java.io.File) ProviderFactory(org.gradle.api.provider.ProviderFactory) ComponentName(dev.nokee.platform.base.internal.ComponentName) ProjectLayout(org.gradle.api.file.ProjectLayout) ObjectFactory(org.gradle.api.model.ObjectFactory) CppLanguagePlugin(dev.nokee.language.cpp.internal.plugins.CppLanguagePlugin) NokeeStandardToolChainsPlugin(dev.nokee.language.nativebase.internal.toolchains.NokeeStandardToolChainsPlugin) JavaNativeInterfaceLibrary(dev.nokee.platform.jni.JavaNativeInterfaceLibrary) Plugin(org.gradle.api.Plugin) CommandLineArgumentProvider(org.gradle.process.CommandLineArgumentProvider) JniLibrary(dev.nokee.platform.jni.JniLibrary)

Example 13 with CommandLineArgumentProvider

use of org.gradle.process.CommandLineArgumentProvider in project gradle-baseline by palantir.

the class BaselineErrorProne method configureErrorProneOptions.

@SuppressWarnings("UnstableApiUsage")
private static void configureErrorProneOptions(Project project, Provider<File> refasterRulesFile, TaskProvider<CompileRefasterTask> compileRefaster, BaselineErrorProneExtension errorProneExtension, JavaCompile javaCompile, ErrorProneOptions errorProneOptions) {
    if (isDisabled(project)) {
        errorProneOptions.getEnabled().set(false);
    }
    errorProneOptions.getDisableWarningsInGeneratedCode().set(true);
    errorProneOptions.getExcludedPaths().set(excludedPathsRegex());
    errorProneOptions.disable("AutoCloseableMustBeClosed", "CatchSpecificity", "InlineMeSuggester", "PreferImmutableStreamExCollections", "UnusedVariable", // See VarUsage: The var keyword results in illegible code in most cases and should not be used.
    "Varifier");
    errorProneOptions.error("EqualsHashCode", "EqualsIncompatibleType", "StreamResourceLeak", "InputStreamSlowMultibyteRead", "JavaDurationGetSecondsGetNano", "URLEqualsHashCode", "BoxedPrimitiveEquality", "ReferenceEquality");
    // Relax some checks for test code
    if (errorProneOptions.getCompilingTestOnlyCode().get()) {
        errorProneOptions.disable("UnnecessaryLambda");
    }
    if (javaCompile.getName().equals(compileRefaster.getName())) {
        // Don't apply refaster to itself...
        return;
    }
    if (isRefactoring(project)) {
        // Don't attempt to cache since it won't capture the source files that might be modified
        javaCompile.getOutputs().cacheIf(t -> false);
        if (isRefasterRefactoring(project)) {
            javaCompile.dependsOn(compileRefaster);
            errorProneOptions.getErrorproneArgumentProviders().add(new CommandLineArgumentProvider() {

                // intentionally not using a lambda to reduce gradle warnings
                @Override
                public Iterable<String> asArguments() {
                    String file = refasterRulesFile.get().getAbsolutePath();
                    return new File(file).exists() ? ImmutableList.of("-XepPatchChecks:refaster:" + file, "-XepPatchLocation:IN_PLACE") : Collections.emptyList();
                }
            });
        }
        if (isErrorProneRefactoring(project)) {
            Optional<SourceSet> maybeSourceSet = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().matching(ss -> javaCompile.getName().equals(ss.getCompileJavaTaskName())).stream().collect(MoreCollectors.toOptional());
            // TODO(gatesn): Is there a way to discover error-prone checks?
            // Maybe service-load from a ClassLoader configured with annotation processor path?
            // https://github.com/google/error-prone/pull/947
            errorProneOptions.getErrorproneArgumentProviders().add(new CommandLineArgumentProvider() {

                // intentionally not using a lambda to reduce gradle warnings
                @Override
                public Iterable<String> asArguments() {
                    // Don't apply checks that have been explicitly disabled
                    Stream<String> errorProneChecks = getSpecificErrorProneChecks(project).orElseGet(() -> getNotDisabledErrorproneChecks(project, errorProneExtension, javaCompile, maybeSourceSet, errorProneOptions));
                    return ImmutableList.of("-XepPatchChecks:" + Joiner.on(',').join(errorProneChecks.iterator()), "-XepPatchLocation:IN_PLACE");
                }
            });
        }
    }
}
Also used : SourceSet(org.gradle.api.tasks.SourceSet) CommandLineArgumentProvider(org.gradle.process.CommandLineArgumentProvider) Stream(java.util.stream.Stream) File(java.io.File) RegularFile(org.gradle.api.file.RegularFile)

Example 14 with CommandLineArgumentProvider

use of org.gradle.process.CommandLineArgumentProvider in project gradle-baseline by palantir.

the class BaselineModuleJvmArgs method apply.

@Override
@SuppressWarnings("checkstyle:MethodLength")
public void apply(Project project) {
    project.getPluginManager().withPlugin("java", unused -> {
        BaselineModuleJvmArgsExtension extension = project.getExtensions().create(EXTENSION_NAME, BaselineModuleJvmArgsExtension.class, project);
        // javac isn't provided `--add-exports` args for the time being due to
        // https://github.com/gradle/gradle/issues/18824
        // However, we set sourceCompatibility in BaselineJavaVersion to opt out of the '--release' flag.
        project.getExtensions().getByType(SourceSetContainer.class).configureEach(sourceSet -> {
            TaskProvider<JavaCompile> javaCompileProvider = project.getTasks().named(sourceSet.getCompileJavaTaskName(), JavaCompile.class);
            javaCompileProvider.configure(javaCompile -> {
                javaCompile.getOptions().getCompilerArgumentProviders().add(new CommandLineArgumentProvider() {

                    @Override
                    public Iterable<String> asArguments() {
                        // The '--release' flag is set when BaselineJavaVersion is not used.
                        if (!project.getPlugins().hasPlugin(BaselineJavaVersion.class)) {
                            project.getLogger().debug("BaselineModuleJvmArgs not applying args to compilation task " + "{} on {} due to lack of BaselineJavaVersion", javaCompile.getName(), project);
                            return ImmutableList.of();
                        }
                        ImmutableList<String> arguments = collectCompilationArgs(project, extension, sourceSet);
                        project.getLogger().debug("BaselineModuleJvmArgs compiling {} on {} with exports: {}", javaCompile.getName(), project, arguments);
                        return arguments;
                    }
                });
            });
            TaskProvider<Task> javadocTaskProvider = null;
            try {
                javadocTaskProvider = project.getTasks().named(sourceSet.getJavadocTaskName());
            } catch (UnknownTaskException e) {
            // skip
            }
            if (javadocTaskProvider != null) {
                javadocTaskProvider.configure(javadocTask -> {
                    javadocTask.doFirst(new Action<Task>() {

                        @Override
                        public void execute(Task task) {
                            // The '--release' flag is set when BaselineJavaVersion is not used.
                            if (!project.getPlugins().hasPlugin(BaselineJavaVersion.class)) {
                                project.getLogger().debug("BaselineModuleJvmArgs not applying args to compilation task " + "{} on {} due to lack of BaselineJavaVersion", task.getName(), project);
                                return;
                            }
                            Javadoc javadoc = (Javadoc) task;
                            MinimalJavadocOptions options = javadoc.getOptions();
                            if (options instanceof CoreJavadocOptions) {
                                CoreJavadocOptions coreOptions = (CoreJavadocOptions) options;
                                ImmutableList<JarManifestModuleInfo> info = collectClasspathInfo(project, sourceSet);
                                List<String> exportValues = Stream.concat(// Compilation only supports exports, so we union with opens.
                                Stream.concat(extension.exports().get().stream(), extension.opens().get().stream()), info.stream().flatMap(item -> Stream.concat(item.exports().stream(), item.opens().stream()))).distinct().sorted().map(item -> item + "=ALL-UNNAMED").collect(ImmutableList.toImmutableList());
                                project.getLogger().debug("BaselineModuleJvmArgs building {} on {} " + "with exports: {}", javadoc.getName(), project, exportValues);
                                if (!exportValues.isEmpty()) {
                                    coreOptions.addMultilineStringsOption("-add-exports").setValue(exportValues);
                                }
                            } else {
                                project.getLogger().error("MinimalJavadocOptions implementation was " + "not CoreJavadocOptions, rather '{}'", options.getClass().getName());
                            }
                        }
                    });
                });
            }
        });
        project.getTasks().withType(Test.class).configureEach(new Action<Test>() {

            @Override
            public void execute(Test test) {
                test.getJvmArgumentProviders().add(new CommandLineArgumentProvider() {

                    @Override
                    public Iterable<String> asArguments() {
                        ImmutableList<String> arguments = collectClasspathArgs(project, extension, test.getClasspath(), OpensMode.RUNTIME);
                        project.getLogger().debug("BaselineModuleJvmArgs executing {} on {} with exports: {}", test.getName(), project, arguments);
                        return arguments;
                    }
                });
            }
        });
        project.getTasks().withType(JavaExec.class).configureEach(new Action<JavaExec>() {

            @Override
            public void execute(JavaExec javaExec) {
                javaExec.getJvmArgumentProviders().add(new CommandLineArgumentProvider() {

                    @Override
                    public Iterable<String> asArguments() {
                        ImmutableList<String> arguments = collectClasspathArgs(project, extension, javaExec.getClasspath(), OpensMode.RUNTIME);
                        project.getLogger().debug("BaselineModuleJvmArgs executing {} on {} with exports: {}", javaExec.getName(), project, arguments);
                        return arguments;
                    }
                });
            }
        });
        project.getTasks().withType(Jar.class).configureEach(new Action<Jar>() {

            @Override
            public void execute(Jar jar) {
                jar.doFirst(new Action<Task>() {

                    @Override
                    public void execute(Task task) {
                        jar.manifest(new Action<Manifest>() {

                            @Override
                            public void execute(Manifest manifest) {
                                addManifestAttribute(jar, manifest, ADD_EXPORTS_ATTRIBUTE, extension.exports());
                                addManifestAttribute(jar, manifest, ADD_OPENS_ATTRIBUTE, extension.opens());
                            }
                        });
                    }
                });
            }
        });
    });
}
Also used : Task(org.gradle.api.Task) Action(org.gradle.api.Action) ImmutableList(com.google.common.collect.ImmutableList) Javadoc(org.gradle.api.tasks.javadoc.Javadoc) SourceSetContainer(org.gradle.api.tasks.SourceSetContainer) CoreJavadocOptions(org.gradle.external.javadoc.CoreJavadocOptions) JavaExec(org.gradle.api.tasks.JavaExec) Test(org.gradle.api.tasks.testing.Test) MinimalJavadocOptions(org.gradle.external.javadoc.MinimalJavadocOptions) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) Manifest(org.gradle.api.java.archives.Manifest) UnknownTaskException(org.gradle.api.UnknownTaskException) BaselineModuleJvmArgsExtension(com.palantir.baseline.extensions.BaselineModuleJvmArgsExtension) CommandLineArgumentProvider(org.gradle.process.CommandLineArgumentProvider) Jar(org.gradle.jvm.tasks.Jar) JavaCompile(org.gradle.api.tasks.compile.JavaCompile)

Aggregations

CommandLineArgumentProvider (org.gradle.process.CommandLineArgumentProvider)14 ImmutableList (com.google.common.collect.ImmutableList)6 Test (org.gradle.api.tasks.testing.Test)4 Internal (org.gradle.api.tasks.Internal)3 File (java.io.File)2 ImmutableSet (com.google.common.collect.ImmutableSet)1 BaselineModuleJvmArgsExtension (com.palantir.baseline.extensions.BaselineModuleJvmArgsExtension)1 CLanguagePlugin (dev.nokee.language.c.internal.plugins.CLanguagePlugin)1 CppLanguagePlugin (dev.nokee.language.cpp.internal.plugins.CppLanguagePlugin)1 ToolChainSelectorInternal (dev.nokee.language.nativebase.internal.ToolChainSelectorInternal)1 NokeeStandardToolChainsPlugin (dev.nokee.language.nativebase.internal.toolchains.NokeeStandardToolChainsPlugin)1 ObjectiveCLanguagePlugin (dev.nokee.language.objectivec.internal.plugins.ObjectiveCLanguagePlugin)1 ObjectiveCppLanguagePlugin (dev.nokee.language.objectivecpp.internal.plugins.ObjectiveCppLanguagePlugin)1 ProjectIdentifier (dev.nokee.model.internal.ProjectIdentifier)1 ModelNodes (dev.nokee.model.internal.core.ModelNodes)1 ModelProperties (dev.nokee.model.internal.core.ModelProperties)1 ModelRegistry (dev.nokee.model.internal.registry.ModelRegistry)1 VariantView (dev.nokee.platform.base.VariantView)1 BaseVariant (dev.nokee.platform.base.internal.BaseVariant)1 ComponentIdentifier (dev.nokee.platform.base.internal.ComponentIdentifier)1