Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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<String> 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<List<FileTree>>) () ->
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<File> javaDirectories(Object android, String projectPath) {
var directories = new ArrayList<File>();
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> T get(Object object, String getter, Class<T> 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);
}
}
Original file line number Diff line number Diff line change
@@ -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).
*
* <p>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<JavaSources> 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<List<FileCollection>>) () -> sourceSets.stream()
.<FileCollection>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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Project> {
// The spotless gradle plugin got renamed to 'com.diffplug.spotless' at version 5.0.0
Expand All @@ -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
Expand All @@ -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 =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<JavaExtension> {
public class SpotlessInterop implements Action<JavaExtension> {
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
Expand All @@ -52,42 +48,40 @@ public abstract class SpotlessInterop implements Action<JavaExtension> {
"(.*/)?(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<Configuration> formatterClasspath;
private final File gradleUserHome;

@Inject
protected abstract ObjectFactory getObjects();

@Inject
public SpotlessInterop(
File projectDir,
SourceSetContainer sourceSets,
JavaSources sources,
NamedDomainObjectProvider<Configuration> 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<List<FileCollection>>) () -> sourceSets.stream()
.map(sourceSet -> sourceSet.getAllJava().filter(new InGeneratedDirectory(projectDir)))
.toList());
return sources.files().filter(new InGeneratedDirectory(projectDir));
}

/**
Expand Down
Loading
Loading