Skip to content

Provide Gradle projects as dependencies #1903

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
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
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2021 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -24,7 +24,6 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;

import com.diffplug.common.base.Errors;
Expand Down Expand Up @@ -157,7 +156,7 @@ public static class State implements Serializable {

/** State constructor expects that all passed items are not modified afterwards */
protected State(String formatterVersion, String formatterStepExt, Provisioner jarProvisioner, List<String> dependencies, Iterable<File> settingsFiles) throws IOException {
this.jarState = JarState.withoutTransitives(dependencies, jarProvisioner);
this.jarState = JarState.from(dependencies, jarProvisioner, false);
this.settingsFiles = FileSignature.signAsList(settingsFiles);
this.formatterStepExt = formatterStepExt;
semanticVersion = convertEclipseVersion(formatterVersion);
Expand Down Expand Up @@ -187,12 +186,6 @@ public Properties getPreferences() {
return preferences.getProperties();
}

/** Returns first coordinate from sorted set that starts with a given prefix.*/
public Optional<String> getMavenCoordinate(String prefix) {
return jarState.getMavenCoordinates().stream()
.filter(coordinate -> coordinate.startsWith(prefix)).findFirst();
}

/**
* Load class based on the given configuration of JAR provider and Maven coordinates.
* Different class loader instances are provided in the following scenarios:
Expand Down
44 changes: 17 additions & 27 deletions lib/src/main/java/com/diffplug/spotless/JarState.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
Expand All @@ -38,46 +37,43 @@
*/
public final class JarState implements Serializable {
private static final long serialVersionUID = 1L;

@Deprecated
private final Set<String> mavenCoordinates;
private final FileSignature fileSignature;

private JarState(Collection<String> mavenCoordinates, FileSignature fileSignature) {
this.mavenCoordinates = new TreeSet<>(mavenCoordinates);
private JarState(FileSignature fileSignature) {
this.fileSignature = fileSignature;
}

/** Provisions the given maven coordinate and its transitive dependencies. */
public static JarState from(String mavenCoordinate, Provisioner provisioner) throws IOException {
return from(Collections.singletonList(mavenCoordinate), provisioner);
public static JarState from(Object dependency, Provisioner provisioner) throws IOException {
final Collection<?> mavenCoordinates;
if (dependency instanceof Collection) {
mavenCoordinates = (Collection<?>) dependency;
} else {
mavenCoordinates = Collections.singletonList(dependency);
}
return from(mavenCoordinates, provisioner);
}

/** Provisions the given maven coordinates and their transitive dependencies. */
public static JarState from(Collection<String> mavenCoordinates, Provisioner provisioner) throws IOException {
return provisionWithTransitives(true, mavenCoordinates, provisioner);
}

/** Provisions the given maven coordinates without their transitive dependencies. */
public static JarState withoutTransitives(Collection<String> mavenCoordinates, Provisioner provisioner) throws IOException {
return provisionWithTransitives(false, mavenCoordinates, provisioner);
public static JarState from(Collection<?> dependencies, Provisioner provisioner) throws IOException {
return from(dependencies, provisioner, true);
}

private static JarState provisionWithTransitives(boolean withTransitives, Collection<String> mavenCoordinates, Provisioner provisioner) throws IOException {
Objects.requireNonNull(mavenCoordinates, "mavenCoordinates");
public static JarState from(Collection<?> dependencies, Provisioner provisioner, boolean withTransitives) throws IOException {
Objects.requireNonNull(dependencies, "dependencies");
Objects.requireNonNull(provisioner, "provisioner");
Set<File> jars = provisioner.provisionWithTransitives(withTransitives, mavenCoordinates);
Set<File> jars = provisioner.provisionWithTransitives(withTransitives, dependencies);
if (jars.isEmpty()) {
throw new NoSuchElementException("Resolved to an empty result: " + mavenCoordinates.stream().collect(Collectors.joining(", ")));
throw new NoSuchElementException("Resolved to an empty result: " + dependencies.stream().map(Object::toString).collect(Collectors.joining(", ")));
}
FileSignature fileSignature = FileSignature.signAsSet(jars);
return new JarState(mavenCoordinates, fileSignature);
return new JarState(fileSignature);
}

/** Wraps the given collection of a files as a JarState, maintaining the order in the Collection. */
public static JarState preserveOrder(Collection<File> jars) throws IOException {
FileSignature fileSignature = FileSignature.signAsList(jars);
return new JarState(Collections.emptySet(), fileSignature);
return new JarState(fileSignature);
}

URL[] jarUrls() {
Expand Down Expand Up @@ -107,10 +103,4 @@ public ClassLoader getClassLoader() {
public ClassLoader getClassLoader(Serializable key) {
return SpotlessCache.instance().classloader(key, this);
}

/** Returns unmodifiable view on sorted Maven coordinates */
@Deprecated
public Set<String> getMavenCoordinates() {
return Collections.unmodifiableSet(mavenCoordinates);
}
}
14 changes: 3 additions & 11 deletions lib/src/main/java/com/diffplug/spotless/Provisioner.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -16,7 +16,6 @@
package com.diffplug.spotless;

import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;

Expand All @@ -25,17 +24,10 @@
* Spotless' dependencies minimal.
*/
public interface Provisioner {
/**
* Given a set of Maven coordinates, returns a set of jars which include all
* of the specified coordinates and optionally their transitive dependencies.
*/
public default Set<File> provisionWithTransitives(boolean withTransitives, String... mavenCoordinates) {
return provisionWithTransitives(withTransitives, Arrays.asList(mavenCoordinates));
}

/**
* Given a set of Maven coordinates, returns a set of jars which include all
* of the specified coordinates and optionally their transitive dependencies.
* the specified coordinates and optionally their transitive dependencies.
*/
public Set<File> provisionWithTransitives(boolean withTransitives, Collection<String> mavenCoordinates);
Set<File> provisionWithTransitives(boolean withTransitives, Collection<?> dependencies);
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ static class DedupingProvisioner implements Provisioner {
}

@Override
public Set<File> provisionWithTransitives(boolean withTransitives, Collection<String> mavenCoordinates) {
Request req = new Request(withTransitives, mavenCoordinates);
public Set<File> provisionWithTransitives(boolean withTransitives, Collection<?> dependencies) {
Request req = new Request(withTransitives, dependencies);
Set<File> result;
synchronized (cache) {
result = cache.get(req);
Expand All @@ -77,7 +77,7 @@ public Set<File> provisionWithTransitives(boolean withTransitives, Collection<St
synchronized (cache) {
result = cache.get(req);
if (result == null) {
result = provisioner.provisionWithTransitives(req.withTransitives, req.mavenCoords);
result = provisioner.provisionWithTransitives(req.withTransitives, req.dependencies);
cache.put(req, result);
}
return result;
Expand All @@ -86,16 +86,16 @@ public Set<File> provisionWithTransitives(boolean withTransitives, Collection<St
}

/** A child Provisioner which retries cached elements only. */
final Provisioner cachedOnly = (withTransitives, mavenCoordinates) -> {
Request req = new Request(withTransitives, mavenCoordinates);
final Provisioner cachedOnly = (withTransitives, dependencies) -> {
Request req = new Request(withTransitives, dependencies);
Set<File> result;
synchronized (cache) {
result = cache.get(req);
}
if (result != null) {
return result;
}
throw new GradleException("Add a step with " + req.mavenCoords + " into the `spotlessPredeclare` block in the root project.");
throw new GradleException("Add a step with " + req.dependencies + " into the `spotlessPredeclare` block in the root project.");
};
}

Expand All @@ -110,14 +110,14 @@ static Provisioner forRootProjectBuildscript(Project project) {
}

private static Provisioner forConfigurationContainer(Project project, ConfigurationContainer configurations, DependencyHandler dependencies) {
return (withTransitives, mavenCoords) -> {
return (withTransitives, deps) -> {
try {
Configuration config = configurations.create("spotless"
+ new Request(withTransitives, mavenCoords).hashCode());
mavenCoords.stream()
+ new Request(withTransitives, deps).hashCode());
deps.stream()
.map(dependencies::create)
.forEach(config.getDependencies()::add);
config.setDescription(mavenCoords.toString());
config.setDescription(deps.toString());
config.setTransitive(withTransitives);
config.setCanBeConsumed(false);
config.setVisible(false);
Expand All @@ -134,7 +134,7 @@ private static Provisioner forConfigurationContainer(Project project, Configurat
throw new GradleException(String.format(
"You need to add a repository containing the '%s' artifact in '%sbuild.gradle'.%n" +
"E.g.: 'repositories { mavenCentral() }'",
mavenCoords, projName), e);
deps, projName), e);
}
};
}
Expand All @@ -144,16 +144,16 @@ private static Provisioner forConfigurationContainer(Project project, Configurat
/** Models a request to the provisioner. */
private static class Request {
final boolean withTransitives;
final ImmutableList<String> mavenCoords;
final ImmutableList<?> dependencies;

public Request(boolean withTransitives, Collection<String> mavenCoords) {
public Request(boolean withTransitives, Collection<?> dependencies) {
this.withTransitives = withTransitives;
this.mavenCoords = ImmutableList.copyOf(mavenCoords);
this.dependencies = ImmutableList.copyOf(dependencies);
}

@Override
public int hashCode() {
return withTransitives ? mavenCoords.hashCode() : ~mavenCoords.hashCode();
return withTransitives ? dependencies.hashCode() : ~dependencies.hashCode();
}

@Override
Expand All @@ -162,15 +162,15 @@ public boolean equals(Object obj) {
return true;
} else if (obj instanceof Request) {
Request o = (Request) obj;
return o.withTransitives == withTransitives && o.mavenCoords.equals(mavenCoords);
return o.withTransitives == withTransitives && o.dependencies.equals(dependencies);
} else {
return false;
}
}

@Override
public String toString() {
String coords = mavenCoords.toString();
String coords = dependencies.toString();
StringBuilder builder = new StringBuilder();
builder.append(coords, 1, coords.length() - 1); // strip off []
if (withTransitives) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* Copyright 2023 DiffPlug
*
* 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.diffplug.gradle.spotless;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.IOException;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

public class GradleProvisionerTest extends GradleIntegrationHarness {
private static final String JUPITER_COORDINATE = "'" + "org.junit.jupiter:junit-jupiter:5.10.0" + "'";
private static final String JUPITER_TRANSITIVE = "junit-jupiter-params-5.10.0.jar, junit-jupiter-engine-5.10.0.jar, junit-jupiter-api-5.10.0.jar, junit-platform-engine-1.10.0.jar, junit-platform-commons-1.10.0.jar, junit-jupiter-5.10.0.jar, opentest4j-1.3.0.jar";

@ParameterizedTest
@ValueSource(booleans = {true, false})
void canResolveMavenCoordinates(boolean withTransitives) throws IOException {
String output = resolveDepsResult(withTransitives, JUPITER_COORDINATE);
assertThat(output).contains(withTransitives ? JUPITER_TRANSITIVE : "junit-jupiter-5.10.0.jar");
}

@ParameterizedTest
@ValueSource(booleans = {true, false})
void canResolveLocalProject(boolean withTransitives) throws IOException {
setFile("settings.gradle").toLines("include 'sub'");
setFile("sub/build.gradle").toLines(
"plugins {",
" id 'java'",
"}",
"repositories { mavenCentral() }",
"dependencies {",
" implementation " + JUPITER_COORDINATE,
"}");
String output = resolveDepsResult(withTransitives, "project(':sub')");
assertThat(output).contains(withTransitives ? JUPITER_TRANSITIVE : "sub.jar");
}

private String resolveDepsResult(boolean withTransitives, Object dep) throws IOException {
setFile("build.gradle").toLines(
"import com.diffplug.gradle.spotless.GradleProvisioner",
"plugins {",
" id 'com.diffplug.spotless'",
"}",
"repositories { mavenCentral() }",
"tasks.register('resolveDeps') {",
" def files = GradleProvisioner.forProject(project)",
String.format(".provisionWithTransitives(%s, [%s])", withTransitives, dep),
" println files.collect { it.getName() }.join(', ')",
"}");
return gradleRunner().withArguments("resolveDeps").build().getOutput();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2016-2020 DiffPlug
* Copyright 2016-2023 DiffPlug
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -60,13 +60,13 @@ public ArtifactResolver(RepositorySystem repositorySystem, RepositorySystemSessi
* Given a set of maven coordinates, returns a set of jars which include all
* of the specified coordinates and optionally their transitive dependencies.
*/
public Set<File> resolve(boolean withTransitives, Collection<String> mavenCoordinates) {
public Set<File> resolve(boolean withTransitives, Collection<?> mavenCoordinates) {
Collection<Exclusion> excludeTransitive = new ArrayList<Exclusion>(1);
if (!withTransitives) {
excludeTransitive.add(EXCLUDE_ALL_TRANSITIVES);
}
List<Dependency> dependencies = mavenCoordinates.stream()
.map(coordinateString -> new DefaultArtifact(coordinateString))
.map(coordinate -> new DefaultArtifact(coordinate.toString()))
.map(artifact -> new Dependency(artifact, null, null, excludeTransitive))
.collect(toList());
CollectRequest collectRequest = new CollectRequest(dependencies, null, repositories);
Expand Down
Loading