Skip to content

Commit f141709

Browse files
authored
Merge pull request #288 from openjavaformat/abashev/please-add-support-for-android-application-and-a
Format the Java files of Android projects
2 parents 57026b0 + 1aa7974 commit f141709

8 files changed

Lines changed: 575 additions & 25 deletions

File tree

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.gradle;
16+
17+
import java.io.File;
18+
import java.lang.reflect.InvocationTargetException;
19+
import java.util.ArrayList;
20+
import java.util.Collection;
21+
import java.util.List;
22+
import java.util.concurrent.Callable;
23+
import org.gradle.api.GradleException;
24+
import org.gradle.api.Project;
25+
import org.gradle.api.file.FileCollection;
26+
import org.gradle.api.file.FileTree;
27+
import org.jspecify.annotations.Nullable;
28+
29+
/**
30+
* The Java files of an Android project: those in the {@code java.srcDirs} of every source set of its {@code android}
31+
* extension, main, test and androidTest, and those of the build types and flavors.
32+
*
33+
* <p>Read by reflection. The plugin has no dependency on the Android Gradle plugin: it never brings a version of its
34+
* 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
35+
* a project that applies the plugin may not see. The three getters it calls are those of the Android DSL.
36+
*/
37+
final class AndroidSources {
38+
39+
/** The Android plugins whose {@code android} extension has {@code sourceSets}. None of them applies java. */
40+
static final List<String> PLUGIN_IDS = List.of(
41+
"com.android.application", "com.android.library", "com.android.dynamic-feature", "com.android.test");
42+
43+
private AndroidSources() {}
44+
45+
/**
46+
* The Java files of the project's Android source sets. A callable: the source sets of the build types and flavors
47+
* are added once the build script declares them, after the plugin is applied.
48+
*/
49+
static FileCollection javaFiles(Project project) {
50+
var android = project.getExtensions().getByName("android");
51+
var objects = project.getObjects();
52+
var projectPath = project.getPath();
53+
return objects.fileCollection().from((Callable<List<FileTree>>) () ->
54+
javaDirectories(android, projectPath).stream()
55+
.map(dir -> objects.fileTree().from(dir).matching(files -> files.include("**/*.java")))
56+
.toList());
57+
}
58+
59+
/** The {@code java.srcDirs} of every source set of {@code android}, the project's Android extension. */
60+
static List<File> javaDirectories(Object android, String projectPath) {
61+
var directories = new ArrayList<File>();
62+
for (var sourceSet : get(android, "getSourceSets", Iterable.class, projectPath)) {
63+
var java = get(sourceSet, "getJava", Object.class, projectPath);
64+
for (var directory : get(java, "getSrcDirs", Collection.class, projectPath)) {
65+
if (!(directory instanceof File file)) {
66+
throw unreadable(projectPath, "getSrcDirs() holds " + describe(directory) + ", not a File", null);
67+
}
68+
directories.add(file);
69+
}
70+
}
71+
return directories;
72+
}
73+
74+
private static <T> T get(Object object, String getter, Class<T> type, String projectPath) {
75+
@Nullable Object value;
76+
try {
77+
value = object.getClass().getMethod(getter).invoke(object);
78+
} catch (NoSuchMethodException | IllegalAccessException e) {
79+
throw unreadable(projectPath, object.getClass().getName() + " has no public " + getter + "()", e);
80+
} catch (InvocationTargetException e) {
81+
throw unreadable(projectPath, getter + "() failed", e.getCause());
82+
}
83+
if (!type.isInstance(value)) {
84+
throw unreadable(
85+
projectPath, getter + "() returned " + describe(value) + ", not a " + type.getName(), null);
86+
}
87+
return type.cast(value);
88+
}
89+
90+
private static String describe(@Nullable Object value) {
91+
return value == null ? "null" : "a " + value.getClass().getName();
92+
}
93+
94+
private static GradleException unreadable(String projectPath, String detail, @Nullable Throwable cause) {
95+
return new GradleException(
96+
"open-java-format could not read android.sourceSets[*].java.srcDirs of project " + projectPath
97+
+ ", the directories it formats: " + detail + ". This version of the Android Gradle plugin"
98+
+ " may need a newer open-java-format; please report it at"
99+
+ " https://github.com/openjavaformat/open-java-format/issues",
100+
cause);
101+
}
102+
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
* Licensed under the Apache License, Version 2.0 (the "License");
3+
* you may not use this file except in compliance with the License.
4+
* You may obtain a copy of the License at
5+
*
6+
* http://www.apache.org/licenses/LICENSE-2.0
7+
*
8+
* Unless required by applicable law or agreed to in writing, software
9+
* distributed under the License is distributed on an "AS IS" BASIS,
10+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
* See the License for the specific language governing permissions and
12+
* limitations under the License.
13+
*/
14+
15+
package com.palantir.javaformat.gradle;
16+
17+
import java.util.List;
18+
import java.util.concurrent.Callable;
19+
import java.util.concurrent.atomic.AtomicBoolean;
20+
import org.gradle.api.Action;
21+
import org.gradle.api.Project;
22+
import org.gradle.api.file.FileCollection;
23+
import org.gradle.api.plugins.JavaPluginExtension;
24+
25+
/**
26+
* The Java files of a project that has Java code: one with the java plugin, or with an Android plugin, which applies
27+
* java-base but not java and leaves the java extension's source sets empty (#284).
28+
*
29+
* <p>Public, as a parameter of {@link SpotlessInterop}'s constructor, which Gradle calls from a class it generates.
30+
*/
31+
public final class JavaSources {
32+
33+
private final FileCollection files;
34+
private final boolean spotlessTarget;
35+
36+
private JavaSources(FileCollection files, boolean spotlessTarget) {
37+
this.files = files;
38+
this.spotlessTarget = spotlessTarget;
39+
}
40+
41+
/**
42+
* Runs the action once, with the project's Java sources, when the project gets the java plugin or one of
43+
* {@link AndroidSources#PLUGIN_IDS}, in whatever order the build applies them.
44+
*/
45+
static void whenPresent(Project project, Action<JavaSources> action) {
46+
var done = new AtomicBoolean();
47+
project.getPluginManager().withPlugin("java", _javaPlugin -> {
48+
if (done.compareAndSet(false, true)) {
49+
action.execute(jvm(project));
50+
}
51+
});
52+
for (var id : AndroidSources.PLUGIN_IDS) {
53+
project.getPluginManager().withPlugin(id, _androidPlugin -> {
54+
if (done.compareAndSet(false, true)) {
55+
action.execute(new JavaSources(AndroidSources.javaFiles(project), true));
56+
}
57+
});
58+
}
59+
}
60+
61+
/**
62+
* The Java files of the java extension's source sets, which Spotless formats by default. A callable, so that source
63+
* sets added after the plugin count too.
64+
*/
65+
private static JavaSources jvm(Project project) {
66+
var sourceSets =
67+
project.getExtensions().getByType(JavaPluginExtension.class).getSourceSets();
68+
return new JavaSources(
69+
project.getObjects().fileCollection().from((Callable<List<FileCollection>>) () -> sourceSets.stream()
70+
.<FileCollection>map(sourceSet -> sourceSet.getAllJava())
71+
.toList()),
72+
false);
73+
}
74+
75+
/** The project's Java files. */
76+
FileCollection files() {
77+
return files;
78+
}
79+
80+
/**
81+
* Whether Spotless needs {@link #files} as its target: its own default is the java extension's source sets, which
82+
* holds nothing in an Android project.
83+
*/
84+
boolean spotlessTarget() {
85+
return spotlessTarget;
86+
}
87+
}

‎gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/PalantirJavaFormatPlugin.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public void apply(Project project) {
4949

5050
project.getPlugins().apply(PalantirJavaFormatSpotlessPlugin.class);
5151

52-
project.getPlugins().withId("java", p -> {
52+
JavaSources.whenPresent(project, _sources -> {
5353
var formatterClasspath = FormatterClasspath.of(project);
5454
var nativeImage = FormatterClasspath.nativeImageOf(project);
5555

‎gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/PalantirJavaFormatSpotlessPlugin.java‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
import org.gradle.api.Plugin;
2222
import org.gradle.api.Project;
2323
import org.gradle.api.Task;
24-
import org.gradle.api.plugins.JavaPluginExtension;
2524

2625
public abstract class PalantirJavaFormatSpotlessPlugin implements Plugin<Project> {
2726
// The spotless gradle plugin got renamed to 'com.diffplug.spotless' at version 5.0.0
@@ -33,7 +32,7 @@ public void apply(Project project) {
3332
Project rootProject = project.getRootProject();
3433
rootProject.getPluginManager().apply(PalantirJavaFormatProviderPlugin.class);
3534

36-
project.getPluginManager().withPlugin("java", _javaPlugin -> {
35+
JavaSources.whenPresent(project, sources -> {
3736
SPOTLESS_PLUGINS.forEach(spotlessPluginId -> project.getPluginManager()
3837
.withPlugin(spotlessPluginId, _spotlessPlugin -> {
3938
// Not before this point: Gradle's decoration of SpotlessInterop loads Spotless classes, which
@@ -43,9 +42,7 @@ public void apply(Project project) {
4342
.newInstance(
4443
SpotlessInterop.class,
4544
project.getProjectDir(),
46-
project.getExtensions()
47-
.getByType(JavaPluginExtension.class)
48-
.getSourceSets(),
45+
sources,
4946
FormatterClasspath.of(project),
5047
project.getGradle().getGradleUserHomeDir());
5148
SpotlessExtension spotlessExtension =

‎gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/SpotlessInterop.java‎

Lines changed: 12 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,6 @@
1919
import com.diffplug.spotless.FormatterStep;
2020
import com.palantir.javaformat.gradle.spotless.PalantirJavaFormatStep;
2121
import java.io.File;
22-
import java.util.List;
23-
import java.util.concurrent.Callable;
2422
import java.util.regex.Pattern;
2523
import javax.inject.Inject;
2624
import org.gradle.api.Action;
@@ -29,15 +27,13 @@
2927
import org.gradle.api.file.FileCollection;
3028
import org.gradle.api.logging.Logger;
3129
import org.gradle.api.logging.Logging;
32-
import org.gradle.api.model.ObjectFactory;
3330
import org.gradle.api.specs.Spec;
34-
import org.gradle.api.tasks.SourceSetContainer;
3531

3632
/**
3733
* Class that exists only to encapsulate accessing spotless classes, so that Gradle can generate a decorated class for
3834
* {@link com.palantir.javaformat.gradle.PalantirJavaFormatSpotlessPlugin} even if spotless is not on the classpath.
3935
*/
40-
public abstract class SpotlessInterop implements Action<JavaExtension> {
36+
public class SpotlessInterop implements Action<JavaExtension> {
4137
private final Logger logger = Logging.getLogger(SpotlessInterop.class);
4238

4339
// 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<JavaExtension> {
5248
"(.*/)?(build/generated[^/]*|src/generated[^/]*|generated_[^/]*src|generated_[^/]*Src|groovy-dsl-plugins)/.+");
5349

5450
private final File projectDir;
55-
private final SourceSetContainer sourceSets;
51+
private final JavaSources sources;
5652
private final NamedDomainObjectProvider<Configuration> formatterClasspath;
5753
private final File gradleUserHome;
5854

59-
@Inject
60-
protected abstract ObjectFactory getObjects();
61-
6255
@Inject
6356
public SpotlessInterop(
6457
File projectDir,
65-
SourceSetContainer sourceSets,
58+
JavaSources sources,
6659
NamedDomainObjectProvider<Configuration> formatterClasspath,
6760
File gradleUserHome) {
6861
this.projectDir = projectDir;
69-
this.sourceSets = sourceSets;
62+
this.sources = sources;
7063
this.formatterClasspath = formatterClasspath;
7164
this.gradleUserHome = gradleUserHome;
7265
}
7366

7467
@Override
7568
public void execute(JavaExtension java) {
69+
if (sources.spotlessTarget()) {
70+
// A target the build script sets in spotless { java { ... } } later replaces this one.
71+
java.target(sources.files());
72+
}
7673
java.targetExclude(generatedSources());
7774
// This is configuration cache safe as happening afterEvaluate
7875
java.addStep(spotlessJavaFormatStep());
7976
}
8077

8178
/**
82-
* The Java files of the source sets that are in a generated directory. Not the patterns themselves: Spotless
83-
* matches a pattern against a file tree of the whole project directory, which every build changes, and the
84-
* configuration cache entry is then never reused (#193). The source sets' files are what Spotless formats by
85-
* default; a callable, so that source sets added after the plugin count too.
79+
* The project's Java files that are in a generated directory. Not the patterns themselves: Spotless matches a
80+
* pattern against a file tree of the whole project directory, which every build changes, and the configuration
81+
* cache entry is then never reused (#193).
8682
*/
8783
private FileCollection generatedSources() {
88-
return getObjects().fileCollection().from((Callable<List<FileCollection>>) () -> sourceSets.stream()
89-
.map(sourceSet -> sourceSet.getAllJava().filter(new InGeneratedDirectory(projectDir)))
90-
.toList());
84+
return sources.files().filter(new InGeneratedDirectory(projectDir));
9185
}
9286

9387
/**

0 commit comments

Comments
 (0)