diff --git a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/AndroidSources.java b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/AndroidSources.java
new file mode 100644
index 000000000..e6fdeb2a9
--- /dev/null
+++ b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/AndroidSources.java
@@ -0,0 +1,102 @@
+/*
+ * 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.javaformat.gradle;
+
+import java.io.File;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.Callable;
+import org.gradle.api.GradleException;
+import org.gradle.api.Project;
+import org.gradle.api.file.FileCollection;
+import org.gradle.api.file.FileTree;
+import org.jspecify.annotations.Nullable;
+
+/**
+ * The Java files of an Android project: those in the {@code java.srcDirs} of every source set of its {@code android}
+ * extension, main, test and androidTest, and those of the build types and flavors.
+ *
+ *
Read by reflection. The plugin has no dependency on the Android Gradle plugin: it never brings a version of its
+ * own into a build that has one, and it does not need the classes of the one the build has, which the class loader of
+ * a project that applies the plugin may not see. The three getters it calls are those of the Android DSL.
+ */
+final class AndroidSources {
+
+ /** The Android plugins whose {@code android} extension has {@code sourceSets}. None of them applies java. */
+ static final List PLUGIN_IDS = List.of(
+ "com.android.application", "com.android.library", "com.android.dynamic-feature", "com.android.test");
+
+ private AndroidSources() {}
+
+ /**
+ * The Java files of the project's Android source sets. A callable: the source sets of the build types and flavors
+ * are added once the build script declares them, after the plugin is applied.
+ */
+ static FileCollection javaFiles(Project project) {
+ var android = project.getExtensions().getByName("android");
+ var objects = project.getObjects();
+ var projectPath = project.getPath();
+ return objects.fileCollection().from((Callable>) () ->
+ javaDirectories(android, projectPath).stream()
+ .map(dir -> objects.fileTree().from(dir).matching(files -> files.include("**/*.java")))
+ .toList());
+ }
+
+ /** The {@code java.srcDirs} of every source set of {@code android}, the project's Android extension. */
+ static List javaDirectories(Object android, String projectPath) {
+ var directories = new ArrayList();
+ for (var sourceSet : get(android, "getSourceSets", Iterable.class, projectPath)) {
+ var java = get(sourceSet, "getJava", Object.class, projectPath);
+ for (var directory : get(java, "getSrcDirs", Collection.class, projectPath)) {
+ if (!(directory instanceof File file)) {
+ throw unreadable(projectPath, "getSrcDirs() holds " + describe(directory) + ", not a File", null);
+ }
+ directories.add(file);
+ }
+ }
+ return directories;
+ }
+
+ private static T get(Object object, String getter, Class type, String projectPath) {
+ @Nullable Object value;
+ try {
+ value = object.getClass().getMethod(getter).invoke(object);
+ } catch (NoSuchMethodException | IllegalAccessException e) {
+ throw unreadable(projectPath, object.getClass().getName() + " has no public " + getter + "()", e);
+ } catch (InvocationTargetException e) {
+ throw unreadable(projectPath, getter + "() failed", e.getCause());
+ }
+ if (!type.isInstance(value)) {
+ throw unreadable(
+ projectPath, getter + "() returned " + describe(value) + ", not a " + type.getName(), null);
+ }
+ return type.cast(value);
+ }
+
+ private static String describe(@Nullable Object value) {
+ return value == null ? "null" : "a " + value.getClass().getName();
+ }
+
+ private static GradleException unreadable(String projectPath, String detail, @Nullable Throwable cause) {
+ return new GradleException(
+ "open-java-format could not read android.sourceSets[*].java.srcDirs of project " + projectPath
+ + ", the directories it formats: " + detail + ". This version of the Android Gradle plugin"
+ + " may need a newer open-java-format; please report it at"
+ + " https://github.com/openjavaformat/open-java-format/issues",
+ cause);
+ }
+}
diff --git a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/JavaSources.java b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/JavaSources.java
new file mode 100644
index 000000000..793ba834c
--- /dev/null
+++ b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/JavaSources.java
@@ -0,0 +1,87 @@
+/*
+ * 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.javaformat.gradle;
+
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.gradle.api.Action;
+import org.gradle.api.Project;
+import org.gradle.api.file.FileCollection;
+import org.gradle.api.plugins.JavaPluginExtension;
+
+/**
+ * The Java files of a project that has Java code: one with the java plugin, or with an Android plugin, which applies
+ * java-base but not java and leaves the java extension's source sets empty (#284).
+ *
+ * Public, as a parameter of {@link SpotlessInterop}'s constructor, which Gradle calls from a class it generates.
+ */
+public final class JavaSources {
+
+ private final FileCollection files;
+ private final boolean spotlessTarget;
+
+ private JavaSources(FileCollection files, boolean spotlessTarget) {
+ this.files = files;
+ this.spotlessTarget = spotlessTarget;
+ }
+
+ /**
+ * Runs the action once, with the project's Java sources, when the project gets the java plugin or one of
+ * {@link AndroidSources#PLUGIN_IDS}, in whatever order the build applies them.
+ */
+ static void whenPresent(Project project, Action action) {
+ var done = new AtomicBoolean();
+ project.getPluginManager().withPlugin("java", _javaPlugin -> {
+ if (done.compareAndSet(false, true)) {
+ action.execute(jvm(project));
+ }
+ });
+ for (var id : AndroidSources.PLUGIN_IDS) {
+ project.getPluginManager().withPlugin(id, _androidPlugin -> {
+ if (done.compareAndSet(false, true)) {
+ action.execute(new JavaSources(AndroidSources.javaFiles(project), true));
+ }
+ });
+ }
+ }
+
+ /**
+ * The Java files of the java extension's source sets, which Spotless formats by default. A callable, so that source
+ * sets added after the plugin count too.
+ */
+ private static JavaSources jvm(Project project) {
+ var sourceSets =
+ project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets();
+ return new JavaSources(
+ project.getObjects().fileCollection().from((Callable>) () -> sourceSets.stream()
+ .map(sourceSet -> sourceSet.getAllJava())
+ .toList()),
+ false);
+ }
+
+ /** The project's Java files. */
+ FileCollection files() {
+ return files;
+ }
+
+ /**
+ * Whether Spotless needs {@link #files} as its target: its own default is the java extension's source sets, which
+ * holds nothing in an Android project.
+ */
+ boolean spotlessTarget() {
+ return spotlessTarget;
+ }
+}
diff --git a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/PalantirJavaFormatPlugin.java b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/PalantirJavaFormatPlugin.java
index 46572b5b8..b055bbf11 100644
--- a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/PalantirJavaFormatPlugin.java
+++ b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/PalantirJavaFormatPlugin.java
@@ -49,7 +49,7 @@ public void apply(Project project) {
project.getPlugins().apply(PalantirJavaFormatSpotlessPlugin.class);
- project.getPlugins().withId("java", p -> {
+ JavaSources.whenPresent(project, _sources -> {
var formatterClasspath = FormatterClasspath.of(project);
var nativeImage = FormatterClasspath.nativeImageOf(project);
diff --git a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/PalantirJavaFormatSpotlessPlugin.java b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/PalantirJavaFormatSpotlessPlugin.java
index 11c8a3e63..005af8e98 100644
--- a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/PalantirJavaFormatSpotlessPlugin.java
+++ b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/PalantirJavaFormatSpotlessPlugin.java
@@ -21,7 +21,6 @@
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
-import org.gradle.api.plugins.JavaPluginExtension;
public abstract class PalantirJavaFormatSpotlessPlugin implements Plugin {
// The spotless gradle plugin got renamed to 'com.diffplug.spotless' at version 5.0.0
@@ -33,7 +32,7 @@ public void apply(Project project) {
Project rootProject = project.getRootProject();
rootProject.getPluginManager().apply(PalantirJavaFormatProviderPlugin.class);
- project.getPluginManager().withPlugin("java", _javaPlugin -> {
+ JavaSources.whenPresent(project, sources -> {
SPOTLESS_PLUGINS.forEach(spotlessPluginId -> project.getPluginManager()
.withPlugin(spotlessPluginId, _spotlessPlugin -> {
// Not before this point: Gradle's decoration of SpotlessInterop loads Spotless classes, which
@@ -43,9 +42,7 @@ public void apply(Project project) {
.newInstance(
SpotlessInterop.class,
project.getProjectDir(),
- project.getExtensions()
- .getByType(JavaPluginExtension.class)
- .getSourceSets(),
+ sources,
FormatterClasspath.of(project),
project.getGradle().getGradleUserHomeDir());
SpotlessExtension spotlessExtension =
diff --git a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/SpotlessInterop.java b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/SpotlessInterop.java
index 78ab851c2..edbfaa595 100644
--- a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/SpotlessInterop.java
+++ b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/SpotlessInterop.java
@@ -19,8 +19,6 @@
import com.diffplug.spotless.FormatterStep;
import com.palantir.javaformat.gradle.spotless.PalantirJavaFormatStep;
import java.io.File;
-import java.util.List;
-import java.util.concurrent.Callable;
import java.util.regex.Pattern;
import javax.inject.Inject;
import org.gradle.api.Action;
@@ -29,15 +27,13 @@
import org.gradle.api.file.FileCollection;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
-import org.gradle.api.model.ObjectFactory;
import org.gradle.api.specs.Spec;
-import org.gradle.api.tasks.SourceSetContainer;
/**
* Class that exists only to encapsulate accessing spotless classes, so that Gradle can generate a decorated class for
* {@link com.palantir.javaformat.gradle.PalantirJavaFormatSpotlessPlugin} even if spotless is not on the classpath.
*/
-public abstract class SpotlessInterop implements Action {
+public class SpotlessInterop implements Action {
private final Logger logger = Logging.getLogger(SpotlessInterop.class);
// Generated source directories, which are not formatted: a file is in one when its path in the project directory
@@ -52,42 +48,40 @@ public abstract class SpotlessInterop implements Action {
"(.*/)?(build/generated[^/]*|src/generated[^/]*|generated_[^/]*src|generated_[^/]*Src|groovy-dsl-plugins)/.+");
private final File projectDir;
- private final SourceSetContainer sourceSets;
+ private final JavaSources sources;
private final NamedDomainObjectProvider formatterClasspath;
private final File gradleUserHome;
- @Inject
- protected abstract ObjectFactory getObjects();
-
@Inject
public SpotlessInterop(
File projectDir,
- SourceSetContainer sourceSets,
+ JavaSources sources,
NamedDomainObjectProvider formatterClasspath,
File gradleUserHome) {
this.projectDir = projectDir;
- this.sourceSets = sourceSets;
+ this.sources = sources;
this.formatterClasspath = formatterClasspath;
this.gradleUserHome = gradleUserHome;
}
@Override
public void execute(JavaExtension java) {
+ if (sources.spotlessTarget()) {
+ // A target the build script sets in spotless { java { ... } } later replaces this one.
+ java.target(sources.files());
+ }
java.targetExclude(generatedSources());
// This is configuration cache safe as happening afterEvaluate
java.addStep(spotlessJavaFormatStep());
}
/**
- * The Java files of the source sets that are in a generated directory. Not the patterns themselves: Spotless
- * matches a pattern against a file tree of the whole project directory, which every build changes, and the
- * configuration cache entry is then never reused (#193). The source sets' files are what Spotless formats by
- * default; a callable, so that source sets added after the plugin count too.
+ * The project's Java files that are in a generated directory. Not the patterns themselves: Spotless matches a
+ * pattern against a file tree of the whole project directory, which every build changes, and the configuration
+ * cache entry is then never reused (#193).
*/
private FileCollection generatedSources() {
- return getObjects().fileCollection().from((Callable>) () -> sourceSets.stream()
- .map(sourceSet -> sourceSet.getAllJava().filter(new InGeneratedDirectory(projectDir)))
- .toList());
+ return sources.files().filter(new InGeneratedDirectory(projectDir));
}
/**
diff --git a/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/AndroidSourcesTest.java b/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/AndroidSourcesTest.java
new file mode 100644
index 000000000..305c8cd07
--- /dev/null
+++ b/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/AndroidSourcesTest.java
@@ -0,0 +1,106 @@
+/*
+ * 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.javaformat.gradle;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.File;
+import java.util.List;
+import java.util.Set;
+import org.gradle.api.GradleException;
+import org.jspecify.annotations.Nullable;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Reading the Android extension by reflection, on stand-ins for the Android DSL. {@link AndroidTest} reads the real one
+ * of the oldest Android Gradle plugin we support; these are the extensions it does not expect.
+ */
+final class AndroidSourcesTest {
+
+ private static final File MAIN = new File("/project/src/main/java");
+ private static final File MAIN_KOTLIN = new File("/project/src/main/kotlin");
+ private static final File TEST = new File("/project/src/test/java");
+
+ @Test
+ void reads_the_java_directories_of_every_source_set() {
+ var android = new Android(List.of(new SourceSet(Set.of(MAIN, MAIN_KOTLIN)), new SourceSet(Set.of(TEST))));
+
+ assertThat(AndroidSources.javaDirectories(android, ":app")).containsExactlyInAnyOrder(MAIN, MAIN_KOTLIN, TEST);
+ }
+
+ @Test
+ void names_the_getter_an_extension_does_not_have() {
+ assertThatThrownBy(() -> AndroidSources.javaDirectories(new Object(), ":app"))
+ .isInstanceOf(GradleException.class)
+ .hasMessageContaining("android.sourceSets[*].java.srcDirs of project :app")
+ .hasMessageContaining("java.lang.Object has no public getSourceSets()");
+ }
+
+ @Test
+ void names_what_a_getter_returned_instead_of_files() {
+ var android = new Android(List.of(new SourceSet(Set.of("src/main/java"))));
+
+ assertThatThrownBy(() -> AndroidSources.javaDirectories(android, ":app"))
+ .isInstanceOf(GradleException.class)
+ .hasMessageContaining("getSrcDirs() holds a java.lang.String, not a File");
+ }
+
+ @Test
+ void names_a_getter_that_returned_null() {
+ var android = new Android(null);
+
+ assertThatThrownBy(() -> AndroidSources.javaDirectories(android, ":app"))
+ .isInstanceOf(GradleException.class)
+ .hasMessageContaining("getSourceSets() returned null, not a java.lang.Iterable");
+ }
+
+ /** Public, with public getters, as the classes Gradle generates for the Android DSL are. */
+ public static final class Android {
+ private final @Nullable List sourceSets;
+
+ Android(@Nullable List sourceSets) {
+ this.sourceSets = sourceSets;
+ }
+
+ public @Nullable List getSourceSets() {
+ return sourceSets;
+ }
+ }
+
+ public static final class SourceSet {
+ private final Directories java;
+
+ SourceSet(Set> srcDirs) {
+ this.java = new Directories(srcDirs);
+ }
+
+ public Directories getJava() {
+ return java;
+ }
+ }
+
+ public static final class Directories {
+ private final Set> srcDirs;
+
+ Directories(Set> srcDirs) {
+ this.srcDirs = srcDirs;
+ }
+
+ public Set> getSrcDirs() {
+ return srcDirs;
+ }
+ }
+}
diff --git a/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/AndroidTest.java b/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/AndroidTest.java
new file mode 100644
index 000000000..3f2167d86
--- /dev/null
+++ b/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/AndroidTest.java
@@ -0,0 +1,230 @@
+/*
+ * 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.javaformat.gradle;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import com.palantir.javaformat.gradle.testing.GradleTestProject;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.List;
+import org.gradle.testkit.runner.BuildResult;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.Parameter;
+import org.junit.jupiter.params.ParameterizedClass;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+/**
+ * The plugins in Android projects, which apply java-base but not java (#284): the Spotless step formats the Java files
+ * of the Android source sets, and formatDiff is there. The builds have no Android SDK and need none.
+ */
+@ParameterizedClass(name = "configuration cache {0}")
+@ValueSource(booleans = {true, false})
+final class AndroidTest {
+
+ private static final String UNFORMATTED = "class Main {\n int x;\n}\n";
+ private static final String FORMATTED = "class Main {\n int x;\n}\n";
+
+ private static final String MAIN_JAVA = "src/main/java/test/Main.java";
+
+ /** A file in each kind of source set: main, unit tests, instrumented tests, a build type. */
+ private static final List SOURCE_SET_FILES = List.of(
+ MAIN_JAVA,
+ "src/test/java/test/MainTest.java",
+ "src/androidTest/java/test/MainAndroidTest.java",
+ "src/debug/java/test/Debug.java");
+
+ private static final String ANDROID = """
+ android {
+ namespace = 'test'
+ compileSdk = 36
+ }
+ """;
+
+ @Parameter
+ private boolean configurationCache;
+
+ @TempDir
+ private Path projectDir;
+
+ @ParameterizedTest
+ @ValueSource(strings = {"com.android.application", "com.android.library"})
+ void spotlessApply_formats_the_java_files_of_every_android_source_set(String androidPlugin) {
+ var project = project(androidPlugin);
+ SOURCE_SET_FILES.forEach(file -> project.writeFile(file, UNFORMATTED));
+
+ project.succeeds("spotlessApply");
+
+ assertFormatted(project, SOURCE_SET_FILES);
+ }
+
+ @Test
+ void spotlessCheck_fails_on_an_unformatted_file() {
+ var project = project("com.android.library").writeFile(MAIN_JAVA, UNFORMATTED);
+
+ BuildResult result = project.fails("spotlessCheck");
+
+ // A formatter that fails reports a lint error instead, which fails the check just as well.
+ assertThat(result.getOutput())
+ .contains("format violations")
+ .contains("Main.java")
+ .doesNotContain("lint error");
+ }
+
+ @Test
+ void spotlessApply_leaves_a_generated_source_directory_alone() {
+ var generated = "build/generated/custom/test/Generated.java";
+ var project = project("com.android.library")
+ .buildGradle("android.sourceSets.main.java.srcDir('build/generated/custom')")
+ .writeFile(generated, UNFORMATTED)
+ .writeFile(MAIN_JAVA, UNFORMATTED);
+
+ project.succeeds("spotlessApply");
+
+ assertThat(project.readFile(generated)).isEqualTo(UNFORMATTED);
+ assertThat(project.readFile(MAIN_JAVA)).isEqualTo(FORMATTED);
+ }
+
+ @Test
+ void a_target_in_the_build_script_replaces_the_android_source_sets() {
+ var testJava = "src/test/java/test/MainTest.java";
+ var project = project("com.android.library")
+ .buildGradle("""
+ spotless {
+ java {
+ target 'src/main/java/**/*.java'
+ }
+ }
+ """)
+ .writeFile(MAIN_JAVA, UNFORMATTED)
+ .writeFile(testJava, UNFORMATTED);
+
+ project.succeeds("spotlessApply");
+
+ assertThat(project.readFile(MAIN_JAVA)).isEqualTo(FORMATTED);
+ assertThat(project.readFile(testJava)).isEqualTo(UNFORMATTED);
+ }
+
+ @Test
+ void spotlessApply_formats_a_file_added_after_the_configuration_was_cached() {
+ var added = "src/main/java/test/Added.java";
+ var project = project("com.android.library").writeFile(MAIN_JAVA, UNFORMATTED);
+ project.succeeds("spotlessApply");
+ project.writeFile(added, UNFORMATTED);
+
+ BuildResult result = project.succeeds("spotlessApply");
+
+ assertThat(project.readFile(added)).isEqualTo(FORMATTED);
+ if (configurationCache) {
+ // A target that walked the source directories at configuration time would make every new file a reason to
+ // configure again (#193).
+ assertThat(result.getOutput()).contains("Configuration cache entry reused.");
+ }
+ }
+
+ @Test
+ void formatDiff_formats_the_changed_lines_without_spotless() throws IOException, InterruptedException {
+ var project = new GradleTestProject(projectDir)
+ .configurationCache(configurationCache)
+ .withAndroidGradlePlugin()
+ .withoutSpotlessOnClasspath()
+ .plugins("com.android.library", "dev.openjavaformat.java-format")
+ .withJavacInternalExports()
+ .buildGradle(ANDROID)
+ .writeFile(MAIN_JAVA, "class Main {}\n");
+ commitAll(project);
+ project.writeFile(MAIN_JAVA, UNFORMATTED);
+
+ project.succeeds("formatDiff");
+
+ assertThat(project.readFile(MAIN_JAVA)).isEqualTo(FORMATTED);
+ }
+
+ @Test
+ void spotlessApply_formats_android_and_java_subprojects_in_a_parallel_build() {
+ // As in the report of #284: the plugins declared in the root project and applied by each subproject.
+ var project = new GradleTestProject(projectDir)
+ .configurationCache(configurationCache)
+ .withAndroidGradlePlugin()
+ .pluginsNotApplied(
+ "com.android.application",
+ "com.android.library",
+ "dev.openjavaformat.java-format",
+ "com.diffplug.spotless")
+ .subprojects("app", "androidlibrary", "javalibrary")
+ .withJavacInternalExports();
+ subproject(project, "app", "com.android.application", ANDROID);
+ subproject(project, "androidlibrary", "com.android.library", ANDROID);
+ subproject(project, "javalibrary", "java-library", "");
+
+ project.succeeds("spotlessApply", "--parallel");
+
+ assertFormatted(
+ project, List.of("app/" + MAIN_JAVA, "androidlibrary/" + MAIN_JAVA, "javalibrary/" + MAIN_JAVA));
+ }
+
+ private GradleTestProject project(String androidPlugin) {
+ return new GradleTestProject(projectDir)
+ .configurationCache(configurationCache)
+ .withAndroidGradlePlugin()
+ .plugins(androidPlugin, "dev.openjavaformat.java-format", "com.diffplug.spotless")
+ .withJavacInternalExports()
+ .buildGradle(ANDROID);
+ }
+
+ private static void subproject(GradleTestProject project, String name, String plugin, String script) {
+ project.writeFile(name + "/build.gradle", """
+ plugins {
+ id '%s'
+ id 'dev.openjavaformat.java-format'
+ id 'com.diffplug.spotless'
+ }
+
+ %s""".formatted(plugin, script))
+ .writeFile(name + "/" + MAIN_JAVA, UNFORMATTED);
+ }
+
+ private static void assertFormatted(GradleTestProject project, List files) {
+ for (var file : files) {
+ assertThat(project.readFile(file)).as(file).isEqualTo(FORMATTED);
+ }
+ }
+
+ /** Makes the project a throwaway repository with everything committed, for formatDiff to diff against. */
+ private static void commitAll(GradleTestProject project) throws IOException, InterruptedException {
+ git(project, "init");
+ git(project, "config", "user.name", "Foo");
+ git(project, "config", "user.email", "foo@bar.com");
+ // The repository this runs in may sign commits; a throwaway one has no key to sign with.
+ git(project, "config", "commit.gpgsign", "false");
+ git(project, "add", ".");
+ git(project, "commit", "-m", "Commit");
+ }
+
+ private static void git(GradleTestProject project, String... args) throws IOException, InterruptedException {
+ var command = new String[args.length + 1];
+ command[0] = "git";
+ System.arraycopy(args, 0, command, 1, args.length);
+ var exitCode = new ProcessBuilder(command)
+ .directory(project.path().toFile())
+ .start()
+ .waitFor();
+ if (exitCode != 0) {
+ throw new RuntimeException("git " + String.join(" ", args) + " failed with exit code " + exitCode);
+ }
+ }
+}
diff --git a/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/testing/GradleTestProject.java b/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/testing/GradleTestProject.java
index bfa6faa89..47990f65f 100644
--- a/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/testing/GradleTestProject.java
+++ b/gradle-open-java-format/src/test/java/com/palantir/javaformat/gradle/testing/GradleTestProject.java
@@ -56,6 +56,12 @@ public final class GradleTestProject {
*/
private static final String GRADLE_VERSION = System.getProperty("testkit.gradleVersion", "9.3.1");
+ /**
+ * The Android Gradle plugin of {@link #withAndroidGradlePlugin}: the oldest we claim to support, the oldest that runs
+ * on the oldest Gradle above.
+ */
+ public static final String ANDROID_GRADLE_PLUGIN_VERSION = "9.1.1";
+
/** Written by java-gradle-plugin: the classpath {@link GradleRunner#withPluginClasspath()} injects. */
private static final String PLUGIN_METADATA = "plugin-under-test-metadata.properties";
@@ -68,6 +74,7 @@ public final class GradleTestProject {
private boolean configurationCache = true;
private boolean spotlessOnClasspath = true;
private boolean repositories = true;
+ private boolean androidGradlePlugin;
private Optional buildCacheDir = Optional.empty();
public GradleTestProject(Path projectDir) {
@@ -147,6 +154,17 @@ public GradleTestProject withoutRepositories() {
return this;
}
+ /**
+ * Lets the build scripts apply com.android.application and com.android.library without a version: settings.gradle
+ * resolves them from Google's Maven repository. They are not put next to the plugin under test, which reads the
+ * Android extension by reflection and needs none of its classes, as in a real build that has a version of its own.
+ * The builds need no Android SDK for anything but Android's own tasks.
+ */
+ public GradleTestProject withAndroidGradlePlugin() {
+ this.androidGradlePlugin = true;
+ return this;
+ }
+
/**
* Leaves the Spotless jars out of the classpath injected next to the plugin under test. build.gradle puts them there
* so that generated projects can apply Spotless, which gives every other test Spotless classes whether it applies
@@ -261,7 +279,23 @@ private void write() {
""");
script.append(buildGradle);
- StringBuilder settings = new StringBuilder("rootProject.name = 'test-project'\n");
+ StringBuilder settings = new StringBuilder();
+ if (androidGradlePlugin) {
+ settings.append("""
+ pluginManagement {
+ repositories {
+ google()
+ mavenCentral()
+ }
+ plugins {
+ id 'com.android.application' version '%1$s'
+ id 'com.android.library' version '%1$s'
+ }
+ }
+
+ """.formatted(ANDROID_GRADLE_PLUGIN_VERSION));
+ }
+ settings.append("rootProject.name = 'test-project'\n");
for (var name : subprojects) {
settings.append("include '").append(name).append("'\n");
// Gradle refuses a project whose directory is missing.