Skip to content

Commit

Permalink
add arch condition to check for any transitive dependency
Browse files Browse the repository at this point in the history
Issue: TNG#780
Signed-off-by: e.solutions <info@esolutions.de>
on-behalf-of: @e-esolutions-GmbH <info@esolutions.de>
  • Loading branch information
Pfoerd committed Jun 7, 2022
1 parent 6862363 commit 2269932
Show file tree
Hide file tree
Showing 5 changed files with 279 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*
* 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.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.tngtech.archunit.base.DescribedPredicate;
import com.tngtech.archunit.core.domain.Dependency;
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;

public class AnyTransitiveDependencyCondition extends ArchCondition<JavaClass> {

private final DescribedPredicate<? super JavaClass> conditionPredicate;
private final Set<JavaClass> allClasses = new HashSet<>();

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

this.conditionPredicate = checkNotNull(conditionPredicate);
}

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

@Override
public void check(JavaClass item, ConditionEvents events) {
getDirectDependencyTargets(item)
.filter(not(allClasses::contains))
.map(this::findFirstPathToTransitiveDependency)
.filter(Objects::nonNull)
.map(dependencyPath -> createTransitivePathFoundEvent(item, dependencyPath))
.forEach(events::add);
}

/**
* @return the first dependency path to a matching class including the source class or null if there is none
*/
private LinkedList<JavaClass> findFirstPathToTransitiveDependency(JavaClass clazz) {
LinkedList<JavaClass> transitivePath = new LinkedList<>();
if (addDependenciesToPathFrom(clazz, transitivePath, new HashSet<>())) {
transitivePath.add(clazz);
return transitivePath;
}
return null;
}

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

analyzedClasses.add(clazz);

Optional<JavaClass> firstMatchingTransitiveDependency = getDirectDependencyTargets(clazz)
.filter(not(allClasses::contains)) // avoid circles
.filter(not(analyzedClasses::contains))
.filter(it -> addDependenciesToPathFrom(it, dependencyPath, analyzedClasses))
.findFirst();

firstMatchingTransitiveDependency.ifPresent(dependencyPath::add);
return firstMatchingTransitiveDependency.isPresent();
}

private static Stream<JavaClass> getDirectDependencyTargets(JavaClass item) {
return item.getDirectDependenciesFromSelf().stream().map(Dependency::getTargetClass).map(JavaClass::getBaseComponentType).distinct();
}

private static ConditionEvent createTransitivePathFoundEvent(JavaClass clazz, LinkedList<JavaClass> dependencyPath) {
StringBuilder messageBuilder =
new StringBuilder("Class <" + clazz.getFullName() + "> accesses <" + dependencyPath.getLast().getFullName() + ">");
if (dependencyPath.size() > 1) {
messageBuilder
.append(" which transitively accesses e.g. ")
.append(dependencyPath.subList(0, dependencyPath.size()).stream()
.map(it -> String.format("<%s>", it.getFullName()))
.collect(Collectors.joining(" <- ")));

}
return SimpleConditionEvent.satisfied(clazz, messageBuilder.toString());
}

@SuppressWarnings("unchecked")
private static <T> Predicate<T> not(Predicate<? super T> target) {
Objects.requireNonNull(target);
return (Predicate<T>) target.negate();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,11 @@ public static ArchCondition<JavaClass> transitivelyDependOnClassesThat(final Des
GET_TRANSITIVE_DEPENDENCIES_FROM_SELF);
}

@PublicAPI(usage = ACCESS)
public static ArchCondition<JavaClass> transitivelyDependOnAnyClassesThat(final DescribedPredicate<? super JavaClass> predicate) {
return new AnyTransitiveDependencyCondition(predicate);
}

@PublicAPI(usage = ACCESS)
public static ArchCondition<JavaClass> onlyDependOnClassesThat(final DescribedPredicate<? super JavaClass> predicate) {
return new AllDependenciesCondition(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -524,6 +524,16 @@ public ClassesShouldConjunction onlyDependOnClassesThat(DescribedPredicate<? sup
return addCondition(ArchConditions.onlyDependOnClassesThat(predicate));
}

@Override
public ClassesThat<ClassesShouldConjunction> transitivelyDependOnAnyClassesThat() {
return new ClassesThatInternal<>(predicate -> addCondition(ArchConditions.transitivelyDependOnAnyClassesThat(predicate)));
}

@Override
public ClassesShouldConjunction transitivelyDependOnAnyClassesThat(DescribedPredicate<? super JavaClass> predicate) {
return addCondition(ArchConditions.transitivelyDependOnAnyClassesThat(predicate));
}

@Override
public ClassesThat<ClassesShouldConjunction> transitivelyDependOnClassesThat() {
return new ClassesThatInternal<>(predicate -> addCondition(ArchConditions.transitivelyDependOnClassesThat(predicate)));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1015,6 +1015,48 @@ public interface ClassesShould {
@PublicAPI(usage = ACCESS)
ClassesShouldConjunction onlyDependOnClassesThat(DescribedPredicate<? super JavaClass> predicate);

/**
* Asserts that all classes selected by this rule transitively depend on any matching classes.<br>
* This is a much more efficient variant of {@link #transitivelyDependOnClassesThat()} that can be used to detect transitive dependencies in a
* huge codebase or to classes in large 3rd-party libraries like the Android SDK.
* 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>
* {@link ArchRuleDefinition#noClasses() noClasses()}.{@link GivenClasses#should() should()}.{@link #transitivelyDependOnAnyClassesThat()}.{@link ClassesThat#haveFullyQualifiedName(String) haveFullyQualifiedName(String)}
* </code></pre>
*
* NOTE: 'dependOn' catches wide variety of violations, e.g. having fields of type, having method parameters of type, extending type etc...
*
* @return A syntax element that allows choosing to which classes a transitive dependency should exist
*/
@PublicAPI(usage = ACCESS)
ClassesThat<ClassesShouldConjunction> transitivelyDependOnAnyClassesThat();


/**
* Asserts that all classes selected by this rule transitively depend on any matching classes.<br>
* This is a much more efficient variant of {@link #transitivelyDependOnClassesThat()} that can be used to detect transitive dependencies in a
* huge codebase or to classes in large 3rd-party libraries like the Android SDK.
* 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>
* {@link ArchRuleDefinition#noClasses() noClasses()}.{@link GivenClasses#should() should()}.{@link #transitivelyDependOnAnyClassesThat(DescribedPredicate) transitivelyDependOnAnyClassesThat(myPredicate)}
* </code></pre>
*
* NOTE: 'dependOn' catches wide variety of violations, e.g. having fields of type, having method parameters of type, extending type etc...
*
* @param predicate Determines which {@link JavaClass JavaClasses} match the dependency target
* @return A syntax element that can either be used as working rule, or to continue specifying a more complex rule
*/
@PublicAPI(usage = ACCESS)
ClassesShouldConjunction transitivelyDependOnAnyClassesThat(DescribedPredicate<? super JavaClass> predicate);

/**
* Asserts that all classes selected by this rule transitively depend on certain classes.<br>
* NOTE: This usually makes more sense the negated way, e.g.
Expand Down
Loading

0 comments on commit 2269932

Please sign in to comment.