Skip to content
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

print out suggestion for module dependencies inclusion in useful format #733

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Expand Up @@ -19,20 +19,13 @@
import com.google.common.collect.Sets;
import com.google.common.collect.Streams;
import com.palantir.baseline.plugins.BaselineExactDependencies;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.ResolvedArtifact;
import org.gradle.api.artifacts.ResolvedDependency;
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
import org.gradle.api.file.FileCollection;
import org.gradle.api.provider.ListProperty;
import org.gradle.api.provider.Property;
Expand All @@ -42,6 +35,10 @@
import org.gradle.api.tasks.InputFiles;
import org.gradle.api.tasks.TaskAction;

import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;

public class CheckImplicitDependenciesTask extends DefaultTask {

private final ListProperty<Configuration> dependenciesConfigurations;
Expand Down Expand Up @@ -80,11 +77,9 @@ public final void checkImplicitDependencies() {
.filter(artifact -> !shouldIgnore(artifact))
.collect(Collectors.toList());
if (!usedButUndeclared.isEmpty()) {
// TODO(dfox): suggest project(':project-name') when a jar actually comes from this project!

String suggestion = usedButUndeclared.stream()
.map(artifact -> String.format(" implementation '%s:%s'",
artifact.getModuleVersion().getId().getGroup(),
artifact.getModuleVersion().getId().getName()))
.map(artifact -> getSuggestionString(artifact))
.sorted()
.collect(Collectors.joining("\n", " dependencies {\n", "\n }"));

Expand All @@ -97,6 +92,30 @@ public final void checkImplicitDependencies() {
}
}

private String getSuggestionString(ResolvedArtifact artifact) {
String artifactNameString;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this would be an OK use of a ternary operator - seems less gross than the artifactNameString thingy

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

if (isProjectArtifact(artifact)) {
artifactNameString = String.format("project('%s')",
((ProjectComponentIdentifier)artifact.getId().getComponentIdentifier()).getProjectPath());
}
else {
artifactNameString = String.format("'%s:%s'",
artifact.getModuleVersion().getId().getGroup(),
artifact.getModuleVersion().getId().getName());
}
return String.format(" implementation %s", artifactNameString);
}

/**
* Return true if the resolved artifact is derived from a project in the current build rather than an
* external jar.
* @param artifact
* @return
*/
private boolean isProjectArtifact(ResolvedArtifact artifact) {
return artifact.getId().getComponentIdentifier() instanceof ProjectComponentIdentifier;
}

/** All classes which are mentioned in this project's source code. */
private Set<String> referencedClasses() {
return Streams.stream(sourceClasses.get().iterator())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ package com.palantir.baseline
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.TaskOutcome

import java.nio.file.Files

class BaselineExactDependenciesTest extends AbstractPluginTest {

def standardBuildFile = '''
Expand Down Expand Up @@ -99,4 +101,90 @@ class BaselineExactDependenciesTest extends AbstractPluginTest {
result.task(':checkImplicitDependencies').getOutcome() == TaskOutcome.FAILED
result.output.contains("Found 1 implicit dependencies")
}

def 'checkImplicitDependencies succeeds when cross-project dependencies properly declared'() {
when:
setupMultiProject()

then:
BuildResult result = with(':sub-project-with-deps:checkImplicitDependencies', '--stacktrace').withDebug(true).build()
result.task(':sub-project-with-deps:classes').getOutcome() == TaskOutcome.SUCCESS
result.task(':sub-project-with-deps:checkImplicitDependencies').getOutcome() == TaskOutcome.SUCCESS

}

def 'checkImplicitDependencies fails on transitive project dependency'() {
when:
setupMultiProject()

then:
BuildResult result = with('checkImplicitDependencies', '--stacktrace').withDebug(true).buildAndFail()
result.task(':classes').getOutcome() == TaskOutcome.SUCCESS
result.task(':checkImplicitDependencies').getOutcome() == TaskOutcome.FAILED
result.output.contains("Found 1 implicit dependencies")
result.output.contains("implementation project(':sub-project-no-deps')")
}

/**
* Sets up a multi-module project with 2 sub projects. The root project has a transitive dependency on sub-project-no-deps
* and so checkImplicitDependencies should fail on it.
*/
private void setupMultiProject() {
buildFile << standardBuildFile
buildFile << """
allprojects {
apply plugin: 'java'
apply plugin: 'com.palantir.baseline-exact-dependencies'
}
dependencies {
compile project(':sub-project-with-deps')
}
""".stripIndent()

def subProjects = multiProject.create(["sub-project-no-deps", "sub-project-with-deps"])

//properly declare dependency between two sub-projects
subProjects['sub-project-with-deps'].buildGradle << '''
dependencies {
compile project(':sub-project-no-deps')
}
'''.stripIndent()

//sub-project-no-deps has no dependencies
def directory = subProjects['sub-project-no-deps'].directory
File myClass1 = new File(directory, "src/main/java/com/p1/TestClassNoDeps.java")
Files.createDirectories(myClass1.toPath().getParent())
myClass1 << "package com.p1; public class TestClassNoDeps {}"

//write a second class to be referenced in a different place
myClass1 = new File(directory, "src/main/java/com/p1/TestClassNoDeps2.java")
myClass1 << "package com.p1; public class TestClassNoDeps2 {}"

//write class in sub-project-with-deps that uses TestClassNoDeps
File myClass2 = new File(subProjects['sub-project-with-deps'].directory, "src/main/java/com/p2/TestClassWithDeps.java")
Files.createDirectories(myClass2.toPath().getParent())
myClass2 << '''
package com.p2;
import com.p1.TestClassNoDeps;
public class TestClassWithDeps {
void foo() {
System.out.println (new TestClassNoDeps());
}
}
'''.stripIndent()

//Create source file in root project that uses TestClassNoDeps2
File myRootClass = new File(projectDir, "src/main/java/com/p0/RootTestClassWithDeps.java")
Files.createDirectories(myRootClass.toPath().getParent())
myRootClass << '''
package com.p2;
import com.p1.TestClassNoDeps2;
public class RootTestClassWithDeps {
void foo() {
System.out.println (new TestClassNoDeps2());
}
}
'''.stripIndent()

}
}