Skip to content

Commit

Permalink
add ArchCondition to check for transitive dependencies
Browse files Browse the repository at this point in the history
The original implementation had the problem that it reported every single transitive dependency that matched the predicate. This would mean, even if a transitive dependency got reported as violation, all further transitive dependencies of that dependency would still be analyzed and potentially also reported as violation. For rules like

```
noClasses()
  .that().resideInAPackage("..example..")
  .should().transitivelyDependOnClassesThat().resideInAPackage("..some.framework..")
```

this would mean thousands of violations, even for classes that are only reached through other framework classes.

We now do a depth first search approach for all dependency paths that are outgoing from the analyzed classes until we find a matching target. Then we stop and report the path. This way all further dependencies will be omitted and the analysis will complete a lot faster.

Issue: TNG#780
Signed-off-by: e.solutions <[email protected]>
on-behalf-of: @e-esolutions-GmbH <[email protected]>
  • Loading branch information
Pfoerd authored and codecholeric committed Jul 8, 2022
1 parent a3268fb commit 499020a
Show file tree
Hide file tree
Showing 4 changed files with 194 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@
import static com.tngtech.archunit.core.domain.JavaClass.Functions.GET_FIELD_ACCESSES_FROM_SELF;
import static com.tngtech.archunit.core.domain.JavaClass.Functions.GET_METHOD_CALLS_FROM_SELF;
import static com.tngtech.archunit.core.domain.JavaClass.Functions.GET_PACKAGE_NAME;
import static com.tngtech.archunit.core.domain.JavaClass.Functions.GET_TRANSITIVE_DEPENDENCIES_FROM_SELF;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.assignableFrom;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.assignableTo;
import static com.tngtech.archunit.core.domain.JavaClass.Predicates.equivalentTo;
Expand Down Expand Up @@ -305,10 +304,7 @@ public static ArchCondition<JavaClass> dependOnClassesThat(final DescribedPredic

@PublicAPI(usage = ACCESS)
public static ArchCondition<JavaClass> transitivelyDependOnClassesThat(final DescribedPredicate<? super JavaClass> predicate) {
return new AnyDependencyCondition(
"transitively depend on classes that " + predicate.getDescription(),
GET_TARGET_CLASS.is(predicate),
GET_TRANSITIVE_DEPENDENCIES_FROM_SELF);
return new TransitiveDependencyCondition(predicate);
}

@PublicAPI(usage = ACCESS)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* Copyright 2014-2022 TNG Technology Consulting GmbH
*
* 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.tngtech.archunit.lang.conditions;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.google.common.collect.ImmutableList;
import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.lang.ArchCondition;
import com.tngtech.archunit.lang.ConditionEvent;
import com.tngtech.archunit.lang.ConditionEvents;
import com.tngtech.archunit.lang.SimpleConditionEvent;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.getLast;
import static com.tngtech.archunit.lang.ConditionEvent.createMessage;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toSet;

public class TransitiveDependencyCondition extends ArchCondition<JavaClass> {

private final DescribedPredicate<? super JavaClass> conditionPredicate;
private final TransitiveDependencyPath transitiveDependencyPath = new TransitiveDependencyPath();
private Collection<JavaClass> allClasses;

public TransitiveDependencyCondition(DescribedPredicate<? super JavaClass> conditionPredicate) {
super("transitively depend on classes that " + conditionPredicate.getDescription());

this.conditionPredicate = checkNotNull(conditionPredicate);
}

@Override
public void init(Collection<JavaClass> allObjectsToTest) {
this.allClasses = allObjectsToTest;
}

@Override
public void check(JavaClass javaClass, ConditionEvents events) {
boolean hasTransitiveDependency = false;
for (JavaClass target : getDirectDependencyTargetsOutsideOfAnalyzedClasses(javaClass)) {
List<JavaClass> dependencyPath = transitiveDependencyPath.findPathTo(target);
if (!dependencyPath.isEmpty()) {
events.add(newTransitiveDependencyPathFoundEvent(javaClass, dependencyPath));
hasTransitiveDependency = true;
}
}
if (!hasTransitiveDependency) {
events.add(newNoTransitiveDependencyPathFoundEvent(javaClass));
}
}

private static ConditionEvent newTransitiveDependencyPathFoundEvent(JavaClass javaClass, List<JavaClass> transitiveDependencyPath) {
String message = String.format("%sdepends on <%s>",
transitiveDependencyPath.size() > 1 ? "transitively " : "",
getLast(transitiveDependencyPath).getFullName());

if (transitiveDependencyPath.size() > 1) {
message += " by [" + transitiveDependencyPath.stream().map(JavaClass::getName).collect(joining("->")) + "]";
}

return SimpleConditionEvent.satisfied(javaClass, createMessage(javaClass, message));
}

private static ConditionEvent newNoTransitiveDependencyPathFoundEvent(JavaClass javaClass) {
return SimpleConditionEvent.violated(javaClass, createMessage(javaClass, "does not transitively depend on any matching class"));
}

private Set<JavaClass> getDirectDependencyTargetsOutsideOfAnalyzedClasses(JavaClass item) {
return item.getDirectDependenciesFromSelf().stream()
.map(dependency -> dependency.getTargetClass().getBaseComponentType())
.filter(targetClass -> !allClasses.contains(targetClass))
.collect(toSet());
}

private class TransitiveDependencyPath {
/**
* @return some outgoing transitive dependency path to the supplied class or empty if there is none
*/
List<JavaClass> findPathTo(JavaClass clazz) {
ImmutableList.Builder<JavaClass> transitivePath = ImmutableList.builder();
addDependenciesToPathFrom(clazz, transitivePath, new HashSet<>());
return transitivePath.build().reverse();
}

private boolean addDependenciesToPathFrom(
JavaClass clazz,
ImmutableList.Builder<JavaClass> dependencyPath,
Set<JavaClass> analyzedClasses
) {
if (conditionPredicate.test(clazz)) {
dependencyPath.add(clazz);
return true;
}

analyzedClasses.add(clazz);

for (JavaClass directDependency : getDirectDependencyTargetsOutsideOfAnalyzedClasses(clazz)) {
if (!analyzedClasses.contains(directDependency)
&& addDependenciesToPathFrom(directDependency, dependencyPath, analyzedClasses)) {
dependencyPath.add(clazz);
return true;
}
}

return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1016,7 +1016,10 @@ public interface ClassesShould {
ClassesShouldConjunction onlyDependOnClassesThat(DescribedPredicate<? super JavaClass> predicate);

/**
* Asserts that all classes selected by this rule transitively depend on certain classes.<br>
* Asserts that all classes selected by this rule transitively depend on any matching classes.<br>
* It focuses on detecting all <strong>direct</strong> dependencies of the selected classes that are themselves matched or have any
* transitive dependencies on matched classes. Thus, it doesn't discover all possible dependency paths but stops at the first match to be fast and
* resource-friendly.<br>
* NOTE: This usually makes more sense the negated way, e.g.
* <p>
* <pre><code>
Expand All @@ -1031,7 +1034,10 @@ public interface ClassesShould {
ClassesThat<ClassesShouldConjunction> transitivelyDependOnClassesThat();

/**
* Asserts that all classes selected by this rule transitively depend on certain classes.<br>
* Asserts that all classes selected by this rule transitively depend on any matching classes.<br>
* It focuses on detecting all <strong>direct</strong> dependencies of the selected classes that are themselves matched or have any
* transitive dependencies on matched classes. Thus, it doesn't discover all possible dependency paths but stops at the first match to be fast and
* resource-friendly.<br>
* NOTE: This usually makes more sense the negated way, e.g.
* <p>
* <pre><code>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaClass.Predicates;
import com.tngtech.archunit.core.domain.JavaClasses;
import com.tngtech.archunit.core.domain.properties.HasName;
import com.tngtech.archunit.core.domain.properties.HasType;
Expand All @@ -36,7 +37,6 @@
import static com.tngtech.archunit.core.domain.properties.HasName.Functions.GET_NAME;
import static com.tngtech.archunit.core.domain.properties.HasName.Predicates.name;
import static com.tngtech.archunit.core.domain.properties.HasType.Functions.GET_RAW_TYPE;
import static com.tngtech.archunit.lang.conditions.ArchConditions.fullyQualifiedName;
import static com.tngtech.archunit.lang.conditions.ArchPredicates.are;
import static com.tngtech.archunit.lang.conditions.ArchPredicates.have;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
Expand Down Expand Up @@ -1711,46 +1711,90 @@ private static class TransitivelyDependOnClassesThatTestCases {
static class TestClass {
DirectlyDependentClass1 directDependency1;
DirectlyDependentClass2 directDependency2;
DirectlyDependentClass3 directDependency3;
}

@SuppressWarnings("unused")
static class TestClassNotViolatingBecauseOnlyDependingOnOtherSelectedClass {
TestClass testClass;
}

@SuppressWarnings("unused")
static class DirectlyDependentClass1 {
TransitivelyDependentClass transitiveDependency1;
Level1TransitivelyDependentClass1 transitiveDependency1;
}

@SuppressWarnings("unused")
static class DirectlyDependentClass2{
static class DirectlyDependentClass2 {
DirectlyDependentClass1 otherDependency;
TransitivelyDependentClass transitiveDependency2;
Level2TransitivelyDependentClass2 transitiveDependency2;
}

static class TransitivelyDependentClass {
static class DirectlyDependentClass3 {
}

@SuppressWarnings("unused")
static class Level1TransitivelyDependentClass1 {
Level2TransitivelyDependentClass1 transitiveDependency1;
}

static class Level2TransitivelyDependentClass1 {
}

@SuppressWarnings("unused")
static class Level2TransitivelyDependentClass2 {
Level2TransitivelyDependentClass1 transitiveDependency1;
}
}

@Test
@DataProvider(value = {"true", "false"})
public void transitivelyDependOnClassesThat_reports_all_transitive_dependencies(boolean viaPredicate) {
Class<?> testClass = TransitivelyDependOnClassesThatTestCases.TestClass.class;
Class<?> testClass1 = TransitivelyDependOnClassesThatTestCases.TestClass.class;
Class<?> testClass2 = TransitivelyDependOnClassesThatTestCases.TestClassNotViolatingBecauseOnlyDependingOnOtherSelectedClass.class;
Class<?> directlyDependentClass1 = TransitivelyDependOnClassesThatTestCases.DirectlyDependentClass1.class;
Class<?> directlyDependentClass2 = TransitivelyDependOnClassesThatTestCases.DirectlyDependentClass2.class;
Class<?> transitivelyDependentClass = TransitivelyDependOnClassesThatTestCases.TransitivelyDependentClass.class;
Class<?> directlyDependentClass3 = TransitivelyDependOnClassesThatTestCases.DirectlyDependentClass3.class;
Class<?> level1TransitivelyDependentClass1 = TransitivelyDependOnClassesThatTestCases.Level1TransitivelyDependentClass1.class;
Class<?> level2TransitivelyDependentClass1 = TransitivelyDependOnClassesThatTestCases.Level2TransitivelyDependentClass1.class;
Class<?> level2TransitivelyDependentClass2 = TransitivelyDependOnClassesThatTestCases.Level2TransitivelyDependentClass2.class;
Class<?>[] matchingTransitivelyDependentClasses =
new Class<?>[]{level2TransitivelyDependentClass1, level2TransitivelyDependentClass2, directlyDependentClass3};

JavaClasses classes = new ClassFileImporter().importClasses(
testClass, directlyDependentClass1, directlyDependentClass2, transitivelyDependentClass
testClass1,
testClass2,
directlyDependentClass1,
directlyDependentClass2,
directlyDependentClass3,
level1TransitivelyDependentClass1,
level2TransitivelyDependentClass1,
level2TransitivelyDependentClass2
);

ClassesShould noClassesShould = noClasses().that().haveFullyQualifiedName(testClass.getName()).should();
ClassesShould noClassesShould = noClasses().that().haveSimpleNameStartingWith("TestClass").should();
ArchRule rule = viaPredicate
? noClassesShould.transitivelyDependOnClassesThat(have(fullyQualifiedName(transitivelyDependentClass.getName())))
: noClassesShould.transitivelyDependOnClassesThat().haveFullyQualifiedName(transitivelyDependentClass.getName());
? noClassesShould.transitivelyDependOnClassesThat(Predicates.belongToAnyOf(matchingTransitivelyDependentClasses))
: noClassesShould.transitivelyDependOnClassesThat().belongToAnyOf(matchingTransitivelyDependentClasses);

assertThatRule(rule).checking(classes)
.hasViolations(2)
.hasViolationMatching(String.format(".*%s\\.%s.* has type .*%s.*",
quote(directlyDependentClass1.getName()), "transitiveDependency1", quote(transitivelyDependentClass.getName())
.hasViolations(3)
.hasViolationMatching(String.format(".*<%s> transitively depends on <(?:%s|%s)> by \\[%s->.*\\] in .*",
quote(testClass1.getName()),
quote(level2TransitivelyDependentClass1.getName()),
quote(level2TransitivelyDependentClass2.getName()),
quote(directlyDependentClass2.getName())
))
.hasViolationMatching(String.format(".*<%s> transitively depends on <%s> by \\[%s->%s->%s\\] in .*",
quote(testClass1.getName()),
quote(level2TransitivelyDependentClass1.getName()),
quote(directlyDependentClass1.getName()),
quote(level1TransitivelyDependentClass1.getName()),
quote(level2TransitivelyDependentClass1.getName())
))
.hasViolationMatching(String.format(".*%s\\.%s.* has type .*%s.*",
quote(directlyDependentClass2.getName()), "transitiveDependency2", quote(transitivelyDependentClass.getName())
.hasViolationMatching(String.format(".*<%s> depends on <%s> in .*",
quote(testClass1.getName()),
quote(directlyDependentClass3.getName())
));
}

Expand Down

0 comments on commit 499020a

Please sign in to comment.