All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.dibog.pomdot.MavenArtifactResolver.kt Maven / Gradle / Ivy

The newest version!
package io.github.dibog.pomdot

import org.jboss.shrinkwrap.resolver.api.maven.Maven
import org.jboss.shrinkwrap.resolver.api.maven.MavenArtifactInfo
import org.jboss.shrinkwrap.resolver.api.maven.MavenResolvedArtifact
import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate
import java.io.File
import java.net.URL

class MavenArtifactResolver private constructor(private val repoUrl : URL) {
    companion object {
        fun usingLocalRepo(): MavenArtifactResolver {
            val localRepo = File("${System.getProperty("user.home")}/.m2/repository").toURI().toURL()
            return MavenArtifactResolver(localRepo)
        }
    }

    private fun fetchArtifacts(coordinate: MavenCoordinate, transitivity: Boolean): List {
        val fragment1 = Maven.configureResolver()
                .withRemoteRepo("id", repoUrl, "default")
                .resolve(coordinate.toCanonicalForm())

        val fragment2 = if(transitivity)
            fragment1.withTransitivity()
        else
            fragment1.withoutTransitivity()

        return fragment2.`as`(MavenResolvedArtifact::class.java)?.toList() ?: listOf()
    }

    private fun resolveArtifact(coordinate: MavenCoordinate): MavenResolvedArtifact {
        return fetchArtifacts(coordinate, false).first { it.coordinate==coordinate }
    }

    fun buildGraph(matcher: CoordinateMatcher, coordinate: MavenCoordinate): Dependency {
        val visited = mutableMapOf()

        fun buildGraphRec(artifact: MavenArtifactInfo): Dependency {
            if(visited.containsKey(artifact.coordinate)) return visited[artifact.coordinate]!!

            val dep = Dependency(artifact)
            visited[artifact.coordinate] = dep
            artifact.dependencies
//                    .debug   { println("ad : ${it.coordinate.groupId}-${it.coordinate.artifactId}") }
                    .filter  { matcher.shouldInclude(it.coordinate) }
//                    .debug   { println("adf: ${it.coordinate.groupId}-${it.coordinate.artifactId}") }
                    .map     { resolveArtifact( it.coordinate ) }
//                    .debug   { println("amf: ${it.coordinate.groupId}-${it.coordinate.artifactId}") }
                    .forEach { dep.addDependency(buildGraphRec(it)) }

            return dep
        }

        val parent = resolveArtifact(coordinate)
        return buildGraphRec(parent)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy