Skip to content
Merged
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* (c) Copyright 2019 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.baseline.extensions;

import javax.inject.Inject;
import org.gradle.api.Project;
import org.gradle.api.provider.SetProperty;
import org.gradle.jvm.toolchain.JavaLanguageVersion;

/**
* Extension to configure {@code --add-exports [VALUE]=ALL-UNNAMED} for the current module.
*/
public class BaselineExportsExtension {

private final SetProperty<String> exports;

@Inject
public BaselineExportsExtension(Project project) {
exports = project.getObjects().setProperty(String.class);
}

/** Target {@link JavaLanguageVersion} for compilation. */
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, this is javadoc for a completely different extension.... updating.

public final SetProperty<String> exports() {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@fawind Extension accessor methods are a bit magical to me, is there a standard way to name this so that I can do something like:

moduleJvmArgs {
  exports += ['java.management/sun.management']
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me quickly check. I think there is some fancy groovy syntax you can use...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated this with a validating setExports(Iterable<String>) which allows us to do exports = ['java.management/sun.management'], so that may be sufficient

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could do something like:

exports() addAll 'java.management/sun.management', 'java.management/sun.other'

We could also add some helper methods to the extension, e.g.:

public final void addExports(String... values) {
    exports.addAll(values);
}

and then we can use it from gradle:

moduleJvmArgs {
    addExports 'java.management/sun.management', 'java.management/sun.other'
}

Copy link
Contributor

@fawind fawind Nov 3, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, didn't see your previous comment. That works very well, didn't think of overloading the setter!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like your varargs example, I'm going to swap to that!

return exports;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The format of a single value here is the full flag value, e.g. "javac.util=ALL-UNNAMED"?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it from the tests, its just the value, so only "javac.util"

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have to read through the JEP again, but there is no other export that you can set besides ALL-UNNAMED?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's the module-package tuple e.g. java.management/sun.management, the =ALL-UNNAMED suffix is implied. I'll add documentation describing this :-)

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public void apply(Project project) {
proj.getPluginManager().apply(BaselineJavaCompilerDiagnostics.class);
proj.getPluginManager().apply(BaselineJavaParameters.class);
proj.getPluginManager().apply(BaselineImmutables.class);
proj.getPluginManager().apply(BaselineModuleJvmArgs.class);
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
/*
* (c) Copyright 2021 Palantir Technologies Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.palantir.baseline.plugins;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.palantir.baseline.extensions.BaselineExportsExtension;
import java.io.IOException;
import java.util.Set;
import java.util.jar.JarFile;
import java.util.stream.Stream;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import org.gradle.api.java.archives.Manifest;
import org.gradle.api.tasks.JavaExec;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.api.tasks.testing.Test;
import org.gradle.jvm.tasks.Jar;
import org.gradle.process.CommandLineArgumentProvider;

/**
* This plugin reuses the {@code Add-Exports} manifest entry to propagate and collect required exports
* from transitive dependencies, and applies them to compilation (for annotation processors) and
* execution (tests, javaExec, etc) for runtime dependencies.
*/
public final class BaselineModuleJvmArgs implements Plugin<Project> {

private static final String EXTENSION_NAME = "moduleJvmArgs";
private static final String ADD_EXPORTS_ATTRIBUTE = "Add-Exports";

private static final Splitter EXPORT_SPLITTER =
Splitter.on(' ').trimResults().omitEmptyStrings();

@Override
public void apply(Project project) {
project.getPluginManager().withPlugin("java", unused -> {
BaselineExportsExtension extension =
project.getExtensions().create(EXTENSION_NAME, BaselineExportsExtension.class, project);

// javac isn't provided `--add-exports` args for the time being due to
// https://github.com/gradle/gradle/issues/18824
if (project.hasProperty("add.exports.to.javac")) {
project.getExtensions().getByType(SourceSetContainer.class).configureEach(sourceSet -> {
JavaCompile javaCompile = project.getTasks()
.named(sourceSet.getCompileJavaTaskName(), JavaCompile.class)
.get();
javaCompile
.getOptions()
.getCompilerArgumentProviders()
// Use an anonymous class because tasks with lambda inputs cannot be cached
.add(new CommandLineArgumentProvider() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As a nitty suggestion, all three CommandLineArgumentProvider are quite similar except for the arguments = ... line. To make this more concise, we might we can define this as a single static class that gets a Provider<List<String>> arguments injected in its constructor?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thoughts on punting this? It would mean plumbing around logging args to differentiate the types of tasks as well

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, no strong opinion on that one!

@Override
public Iterable<String> asArguments() {
// Annotation processors are executed at compile time
ImmutableList<String> arguments =
collectAnnotationProcessorExports(project, extension, sourceSet);
project.getLogger()
.debug(
"BaselineModuleJvmArgs compiling {} on {} with exports: {}",
javaCompile.getName(),
project,
arguments);
return arguments;
}
});
});
}
Comment on lines +64 to +89
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

block is ignored for now, hopefully something becomes of gradle/gradle#18824


project.getTasks().withType(Test.class, new Action<Test>() {

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

@Override
public Iterable<String> asArguments() {
ImmutableList<String> arguments =
collectClasspathExports(project, extension, test.getClasspath());
project.getLogger()
.debug(
"BaselineModuleJvmArgs executing {} on {} with exports: {}",
test.getName(),
project,
arguments);
return arguments;
}
});
}
});

project.getTasks().withType(JavaExec.class, new Action<JavaExec>() {

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

@Override
public Iterable<String> asArguments() {
ImmutableList<String> arguments =
collectClasspathExports(project, extension, javaExec.getClasspath());
Comment on lines +121 to +122
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'll need to duplicate this logic in sls-packaging, or figure out some other way to plumb args through

project.getLogger()
.debug(
"BaselineModuleJvmArgs executing {} on {} with exports: {}",
javaExec.getName(),
project,
arguments);
return arguments;
}
});
}
});

project.getTasks().withType(Jar.class, new Action<Jar>() {
@Override
public void execute(Jar jar) {
jar.manifest(new Action<Manifest>() {
@Override
public void execute(Manifest manifest) {
// Only locally defined exports are applied to jars
Set<String> exports = extension.exports().get();
if (!exports.isEmpty()) {
project.getLogger()
.debug(
"BaselineModuleJvmArgs adding manifest attributes to {} in {}: {}",
jar.getName(),
project,
exports);
manifest.attributes(ImmutableMap.of(ADD_EXPORTS_ATTRIBUTE, String.join(" ", exports)));
} else {
project.getLogger()
.debug(
"BaselineModuleJvmArgs not adding manifest attributes to {} in {}",
jar.getName(),
project);
}
}
});
}
});
});
}

private static ImmutableList<String> collectAnnotationProcessorExports(
Project project, BaselineExportsExtension extension, SourceSet sourceSet) {
return collectClasspathExports(
project,
extension,
project.getConfigurations().getByName(sourceSet.getAnnotationProcessorConfigurationName()));
}

private static ImmutableList<String> collectClasspathExports(
Project project, BaselineExportsExtension extension, FileCollection classpath) {
return Stream.concat(
classpath.getFiles().stream().flatMap(file -> {
try {
if (file.getName().endsWith(".jar") && file.isFile()) {
JarFile jar = new JarFile(file);
String value = jar.getManifest()
.getMainAttributes()
.getValue(ADD_EXPORTS_ATTRIBUTE);
if (Strings.isNullOrEmpty(value)) {
return Stream.empty();
}
project.getLogger()
.debug(
"Found manifest entry {}: {} in jar {}",
ADD_EXPORTS_ATTRIBUTE,
value,
file);
return EXPORT_SPLITTER.splitToStream(value);
}
return Stream.empty();
} catch (IOException e) {
project.getLogger().warn("Failed to check jar {} for manifest attributes", file, e);
return Stream.empty();
}
}),
extension.exports().get().stream())
.distinct()
.sorted()
.flatMap(modulePackagePair -> Stream.of("--add-exports", modulePackagePair + "=ALL-UNNAMED"))
.collect(ImmutableList.toImmutableList());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
implementation-class=com.palantir.baseline.plugins.BaselineModuleJvmArgs