Home > Enterprise >  How can I get a the runtime dependencies along with the coordinates and the JAR file of a Gradle pro
How can I get a the runtime dependencies along with the coordinates and the JAR file of a Gradle pro

Time:11-21

I'm writing a custom Gradle task that needs to iterate all the runtime dependencies (including all the transitive ones). I need the group, the name and the version of each dependency along with the path to the JAR.

The Gradle API does seem to have a ResolvedDependecy but I'm rather lost as to how to get them. https://docs.gradle.org/current/javadoc/org/gradle/api/artifacts/ResolvedDependency.html

There also seems to be rather tricky terminology relating to artifacts, modules, and dependencies https://docs.gradle.org/current/userguide/dependency_management_terminology.html which leaves me rather lost as to how to traverse it? My assumption is that I need to get the runtime configuration using getProject().getConfigurations().getByName("rutime").

CodePudding user response:

I wrote up this snippet of code which yields some results although I'm not sure if this is correct or not. It seems to be the get job done.

import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Stream;

import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ResolvedDependency;

public class Dependencies {

    private static <T> Stream<T> of(T node, Function<T, Collection<T>> childrenFn) {
        return Stream.concat(Stream.of(node), childrenFn.apply(node).stream()
                .flatMap(n -> of(n, childrenFn)));
    }

    private static Stream<ResolvedDependency> of(ResolvedDependency node) {
        return of(node, ResolvedDependency::getChildren);
    }

    @SuppressWarnings("CodeBlock2Expr")
    public static void doIt(Configuration configuration) {
        configuration.getResolvedConfiguration()
                .getFirstLevelModuleDependencies()
                .stream()
                .flatMap(Dependencies::of)
                .flatMap(dependency -> {
                    return dependency.getModuleArtifacts().stream();
                })
                .distinct()
                .forEach(artifact -> {
                    System.out.println(artifact.getFile());
                });
    }
}
  • Related