package com.amadornes.artifactural.gradle; import org.gradle.api.Project; import org.gradle.api.artifacts.*; import org.gradle.internal.impldep.com.google.common.cache.Cache; import org.gradle.internal.impldep.com.google.common.cache.CacheBuilder; import java.io.File; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class DependencyResolver { private final Project project; private final AtomicInteger counter = new AtomicInteger(0); private final Cache>> resolved = CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).build(); public DependencyResolver(Project project) { this.project = project; } /** * Resolves a dependency, downloading the file and its transitives * if not cached and returns the set of files. */ public Set resolveDependency(Dependency dependency) { if (dependency instanceof FileCollectionDependency) { return ((FileCollectionDependency) dependency).getFiles().getFiles(); } String name = dependency.getGroup() + ":" + dependency.getName() + ":" + dependency.getVersion(); if (dependency instanceof ModuleDependency) { Set artifacts = ((ModuleDependency) dependency).getArtifacts(); if (!artifacts.isEmpty()) { DependencyArtifact artifact = artifacts.iterator().next(); name += ":" + artifact.getClassifier() + "@" + artifact.getExtension(); } } // If this dep is being resolved on another thread, let it do it CompletableFuture> future; boolean found = true; synchronized (resolved) { future = resolved.getIfPresent(name); if (future == null) { resolved.put(name, future = new CompletableFuture<>()); found = false; } } if (found) { try { return future.get(); } catch (InterruptedException | ExecutionException ex) { throw new RuntimeException(ex); } } // No other thread is resolving this dep and we've claimed it, so let's go! int currentID = counter.getAndIncrement(); Configuration cfg = project.getConfigurations().maybeCreate("resolve_dep_" + currentID); cfg.getDependencies().add(dependency); Set files = cfg.resolve(); project.getConfigurations().remove(cfg); future.complete(files); return files; } /** * Resolves a dependency, downloading the file and its transitives * if not cached and returns the set of files. */ public Set resolveDependency(Object dependency, boolean transitive) { Dependency dep = project.getDependencies().create(dependency); if (dep instanceof ClientModule) { dep = ((ClientModule) dep).copy().setTransitive(transitive); } return resolveDependency(dep); } }