diff --git a/README.md b/README.md index df71237c7..646b1e822 100644 --- a/README.md +++ b/README.md @@ -195,7 +195,7 @@ Safe Logging can be found at [github.com/palantir/safe-logging](https://github.c - `LogsafeArgName`: Prevent certain named arguments as being logged as safe. Specify unsafe argument names using `LogsafeArgName:UnsafeArgNames` errorProne flag. - `ImplicitPublicBuilderConstructor`: Prevent builders from unintentionally leaking public constructors. - `ImmutablesBuilderMissingInitialization`: Prevent building Immutables.org builders when not all fields have been populated. -- `UnnecessarilyQualified`: Types should not be qualified if they are also imported. +- `UnnecessarilyQualified`: Types should not be qualified if they are also imported. - `DeprecatedGuavaObjects`: `com.google.common.base.Objects` has been obviated by `java.util.Objects`. - `JavaTimeSystemDefaultTimeZone`: Avoid using the system default time zone. @@ -385,16 +385,51 @@ The plugin also adds a `checkJUnitDependencies` to make the migration to JUnit5 3. For repos that use 'snapshot' style testing, it's convenient to have a single command to accept the updated snapshots after a code change. This plugin ensures that if you run tests with `./gradlew test -Drecreate=true`, the system property will be passed down to the running Java process (which can be detected with `Boolean.getBoolean("recreate")`). -## com.palantir.baseline-fix-gradle-java +## com.palantir.baseline-fix-gradle-java (off by default) Fixes up all Java [SourceSets](https://docs.gradle.org/current/userguide/building_java_projects.html#sec:java_source_sets) by marking their deprecated [configurations](https://docs.gradle.org/current/userguide/java_plugin.html#tab:configurations) -- `compile` and `runtime` - as well as the `compileOnly` configuration as not resolvable +- `compile` and `runtime` - as well as the `compileOnly` configuration as not resolvable (can't call resolve on them) and not consumable (can't be depended on from other projects). See [here](https://docs.gradle.org/current/userguide/declaring_dependencies.html#sec:resolvable-consumable-configs) -for a more in-depth discussion on what these terms mean. By configuring them thusly, we are saying that these configurations +for a more in-depth discussion on what these terms mean. By configuring them thusly, we are saying that these configurations now fulfil the "Bucket of dependencies" role described in that document, as they should. This will become the default in Gradle 7 and leaving these as they currently are can cause both unnecessary confusion -(users looking in `compile` instead of `compileClasspath`) and [random crashes](https://github.com/gradle/gradle/issues/11844#issuecomment-585219427). +(users looking in `compile` instead of `compileClasspath`) and [random crashes](https://github.com/gradle/gradle/issues/11844#issuecomment-585219427). + + +## com.palantir.baseline-enable-preview-flag (off by default) + +As described in [JEP 12](https://openjdk.java.net/jeps/12), Java allows you to use shiny new syntax features if you add +the `--enable-preview` flag. However, gradle requires you to add it in multiple places. This plugin can be applied to +within an allprojects block and it will automatically ugprade any project which is already using the latest +sourceCompatibility by adding the necessary `--enable-preview` flags to all of the following task types. + +_Note, this plugin should be used with **caution** because preview features may change or be removed, and it +is undesirable to deeply couple a repo to a particular Java version as it makes upgrading to a new major Java version harder._ + +```gradle +// root build.gradle +allprojects { + apply plugin: 'com.palantir.baseline-enable-preview-flag' +} +``` + +```gradle +// shorthand for the below: +tasks.withType(JavaCompile) { + options.compilerArgs += "--enable-preview" +} +tasks.withType(Test) { + jvmArgs += "--enable-preview" +} +tasks.withType(JavaExec) { + jvmArgs += "--enable-preview" +} +``` + +If you've explicitly specified a lower sourceCompatibility (e.g. for a published API jar), then this plugin is a no-op. +In fact, Java will actually error if you try to switch on the `--enable-preview` flag to get cutting edge syntax +features but set `sourceCompatibility` (or `--release`) to an older Java version. diff --git a/changelog/@unreleased/pr-1549.v2.yml b/changelog/@unreleased/pr-1549.v2.yml new file mode 100644 index 000000000..9507ce681 --- /dev/null +++ b/changelog/@unreleased/pr-1549.v2.yml @@ -0,0 +1,8 @@ +type: feature +feature: + description: |- + Add the `apply plugin: 'com.palantir.baseline-enable-preview-flag'` to your subprojects block to enable the usage of unreleased java features (e.g. records, switch expressions, var keyword etc). + + Note, this plugin is a no-op on any project where you have a low sourceCompatibility. + links: + - https://github.com/palantir/gradle-baseline/pull/1549 diff --git a/gradle-baseline-java/build.gradle b/gradle-baseline-java/build.gradle index 1c4331d53..eb0c34004 100644 --- a/gradle-baseline-java/build.gradle +++ b/gradle-baseline-java/build.gradle @@ -81,6 +81,10 @@ gradlePlugin { id = 'com.palantir.baseline-release-compatibility' implementationClass = 'com.palantir.baseline.plugins.BaselineReleaseCompatibility' } + baselineEnablePreviewFlag { + id = 'com.palantir.baseline-enable-preview-flag' + implementationClass = 'com.palantir.baseline.plugins.BaselineEnablePreviewFlag' + } } } @@ -118,6 +122,9 @@ pluginBundle { baselineReleaseCompatibility { displayName = 'Palantir Baseline Release Compatibility Plugin' } + baselineEnablePreviewFlag { + displayName = 'Palantir Baseline --enable-preview Flag Plugin' + } } } diff --git a/gradle-baseline-java/src/main/groovy/com/palantir/baseline/plugins/BaselineEnablePreviewFlag.java b/gradle-baseline-java/src/main/groovy/com/palantir/baseline/plugins/BaselineEnablePreviewFlag.java new file mode 100644 index 000000000..ad6c10856 --- /dev/null +++ b/gradle-baseline-java/src/main/groovy/com/palantir/baseline/plugins/BaselineEnablePreviewFlag.java @@ -0,0 +1,97 @@ +/* + * (c) Copyright 2020 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 java.util.Collections; +import java.util.List; +import org.gradle.api.JavaVersion; +import org.gradle.api.Plugin; +import org.gradle.api.Project; +import org.gradle.api.plugins.JavaPluginConvention; +import org.gradle.api.provider.Provider; +import org.gradle.api.tasks.JavaExec; +import org.gradle.api.tasks.compile.JavaCompile; +import org.gradle.api.tasks.javadoc.Javadoc; +import org.gradle.api.tasks.testing.Test; +import org.gradle.external.javadoc.CoreJavadocOptions; +import org.gradle.process.CommandLineArgumentProvider; + +public final class BaselineEnablePreviewFlag implements Plugin { + + private static final String FLAG = "--enable-preview"; + + @Override + public void apply(Project project) { + // The idea behind registering a single 'extra property' is that other plugins (like + // sls-packaging) can easily detect this and also also add the --enable-preview jvm arg + Provider enablePreview = project.provider(() -> { + JavaVersion jvmExecutingGradle = JavaVersion.current(); + JavaPluginConvention javaConvention = project.getConvention().findPlugin(JavaPluginConvention.class); + if (javaConvention == null) { + return false; + } + + return javaConvention.getSourceCompatibility() == jvmExecutingGradle; + }); + + project.getExtensions().getExtraProperties().set("enablePreview", enablePreview); + + project.getPlugins().withId("java", _unused -> { + project.getTasks().withType(JavaCompile.class, t -> { + List args = t.getOptions().getCompilerArgumentProviders(); + args.add(new MaybeEnablePreview(enablePreview)); // mutation is gross, but it's the gradle convention + }); + project.getTasks().withType(Test.class, t -> { + t.getJvmArgumentProviders().add(new MaybeEnablePreview(enablePreview)); + }); + project.getTasks().withType(JavaExec.class, t -> { + t.getJvmArgumentProviders().add(new MaybeEnablePreview(enablePreview)); + }); + + // sadly we have to use afterEvaluate because the Javadoc task doesn't support passing in providers + project.afterEvaluate(_unused2 -> { + if (enablePreview.get()) { + JavaVersion sourceCompat = project.getConvention() + .getPlugin(JavaPluginConvention.class) + .getSourceCompatibility(); + project.getTasks().withType(Javadoc.class, t -> { + CoreJavadocOptions options = (CoreJavadocOptions) t.getOptions(); + + // Yes truly javadoc wants a single leading dash, other javac wants a double leading dash. + // We also have to use these manual string options because they don't have first-class methods + // yet (e.g. https://github.com/gradle/gradle/issues/12898) + options.addBooleanOption("-enable-preview", true); + options.addStringOption("source", sourceCompat.getMajorVersion()); + }); + } + }); + }); + } + + private static class MaybeEnablePreview implements CommandLineArgumentProvider { + private final Provider shouldEnable; + + MaybeEnablePreview(Provider shouldEnable) { + this.shouldEnable = shouldEnable; + } + + @Override + public Iterable asArguments() { + return shouldEnable.get() ? Collections.singletonList(FLAG) : Collections.emptyList(); + } + } +} diff --git a/gradle-baseline-java/src/main/resources/META-INF/gradle-plugins/com.palantir.baseline-enable-preview-flag.properties b/gradle-baseline-java/src/main/resources/META-INF/gradle-plugins/com.palantir.baseline-enable-preview-flag.properties new file mode 100644 index 000000000..6ea86cf75 --- /dev/null +++ b/gradle-baseline-java/src/main/resources/META-INF/gradle-plugins/com.palantir.baseline-enable-preview-flag.properties @@ -0,0 +1 @@ +implementation-class=com.palantir.baseline.plugins.BaselineEnablePreviewFlag diff --git a/gradle-baseline-java/src/test/groovy/com/palantir/baseline/plugins/BaselineEnablePreviewFlagTest.groovy b/gradle-baseline-java/src/test/groovy/com/palantir/baseline/plugins/BaselineEnablePreviewFlagTest.groovy new file mode 100644 index 000000000..b4bd1f417 --- /dev/null +++ b/gradle-baseline-java/src/test/groovy/com/palantir/baseline/plugins/BaselineEnablePreviewFlagTest.groovy @@ -0,0 +1,174 @@ +/* + * (c) Copyright 2020 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 nebula.test.IntegrationSpec +import nebula.test.functional.ExecutionResult +import org.gradle.api.JavaVersion +import spock.lang.IgnoreIf + +@IgnoreIf({JavaVersion.current() < JavaVersion.VERSION_14}) +// this class uses records, which were introduced in java 14 +class BaselineEnablePreviewFlagTest extends IntegrationSpec { + + def setupSingleProject(File dir) { + new File(dir, "build.gradle") << ''' + apply plugin: 'java-library' + apply plugin: 'com.palantir.baseline-enable-preview-flag' + apply plugin: 'application' + + application { + mainClass = 'foo.Foo' + } + '''.stripIndent() + + writeSourceFileContainingRecord(dir); + } + + private writeSourceFileContainingRecord(File dir) { + writeJavaSourceFile(''' + package foo; + public class Foo { + /** Hello this is some javadoc. */ + public record Coordinate(int x, int y) {} + + public static void main(String... args) { + System.out.println("Hello, world: " + new Coordinate(1, 2)); + } + } + '''.stripIndent(), dir) + } + + def 'compiles'() { + when: + setupSingleProject(projectDir) + buildFile << ''' + tasks.classes.doLast { + println "COMPILED:" + new File(sourceSets.main.java.outputDir, "foo").list() + } + ''' + ExecutionResult executionResult = runTasks('classes', '-is') + + then: + executionResult.getStandardOutput().contains('Foo$Coordinate.class') + executionResult.getStandardOutput().contains('Foo.class') + } + + def 'javadoc'() { + when: + setupSingleProject(projectDir) + + then: + ExecutionResult executionResult = runTasks('javadoc', '-is') + assert executionResult.getSuccess() ?: executionResult.getStandardOutput() + } + + def 'runs'() { + when: + setupSingleProject(projectDir) + ExecutionResult executionResult = runTasks('run', '-is') + + then: + executionResult.getStandardOutput().contains("Hello, world: Coordinate[x=1, y=2]") + } + + def 'testing works'() { + when: + setupSingleProject(projectDir) + buildFile << ''' + repositories { mavenCentral() } + dependencies { + testImplementation 'junit:junit:4.13.1' + } + ''' + + file('src/test/java/foo/FooTest.java') << ''' + package foo; + public final class FooTest { + @org.junit.Ignore("silly junit4 thinks this 'class' actually contains tests") + record Whatever(int x, int y) {} + + @org.junit.Test + public void whatever() { + Foo.main(); + System.out.println("Hello, world: " + new Whatever(1, 2)); + } + } + '''.stripIndent() + ExecutionResult executionResult = runTasks('test', '-is') + + then: + executionResult.getStandardOutput().contains("Hello, world: Coordinate[x=1, y=2]") + executionResult.getStandardOutput().contains("Hello, world: Whatever[x=1, y=2]") + } + + def 'multiproject'() { + when: + buildFile << ''' + subprojects { + apply plugin: 'java-library' + apply plugin: 'com.palantir.baseline-enable-preview-flag' + } + ''' + + File java14Dir = addSubproject("my-java-14", ''' + apply plugin: 'application' + + application { + mainClass = 'foo.Foo' + } + dependencies { + implementation project(':my-java-14-preview') + } + ''') + writeJavaSourceFile(''' + package bar; + public class Bar { + public static void main(String... args) { + foo.Foo.main(); + } + } + ''', java14Dir); + + File java14PreviewDir = addSubproject("my-java-14-preview") + writeSourceFileContainingRecord(java14PreviewDir) + + + then: + ExecutionResult executionResult = runTasks('run', '-is') + executionResult.getStandardOutput().contains 'Hello, world: Coordinate[x=1, y=2]' + } + + def 'does not always apply'() { + when: + File java8Dir = addSubproject('my-java-8-api', "sourceCompatibility = 8") + buildFile << ''' + subprojects { + apply plugin: 'java-library' + apply plugin: 'com.palantir.baseline-enable-preview-flag' + } + ''' + writeSourceFileContainingRecord(java8Dir) + + ExecutionResult result = runTasks('my-java-8-api:classes', '-is') + + then: + result.getStandardError().contains("use --enable-preview to enable records") + } +} +