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

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

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

import org.jboss.shrinkwrap.resolver.api.maven.coordinate.MavenCoordinate

internal typealias MavenCoordinateCache = MutableMap

sealed class Color {
    abstract val color: String?

    companion object {
        fun colorOf(name: String?) = if(name==null) NoColor else ExistingColor(name)
    }

    object NoColor : Color() {
        override val color = null
    }

    data class ExistingColor(override val color: String) : Color()
}

class CoordinateMatcher(private val includeDep : Regex?, private val excludeDep : Regex?, private val colors : List>) {

    private val includeCache: MavenCoordinateCache = mutableMapOf()
    private val excludeCache : MavenCoordinateCache = mutableMapOf()
    private val colorsCache = mutableMapOf()

    fun shouldInclude(coord: MavenCoordinate): Boolean = when {
        includeDep!=null -> matchesWithCache(includeCache, includeDep, coord)
        excludeDep!=null -> !matchesWithCache(excludeCache, excludeDep, coord)
        else -> true
    }


    fun fetchColor(coord: MavenCoordinate): String? {
        val cachedColor = colorsCache[coord]
        return if(cachedColor!=null) {
            cachedColor.color
        }
        else {
            val colorValue = colors.firstOrNull { (regex, _) ->  regex.matches(coord) }?.second
            colorsCache[coord] = Color.colorOf(colorValue)
            return colorValue
        }
    }

    private fun matchesWithCache(cache: MavenCoordinateCache, regex: Regex, coord: MavenCoordinate): Boolean {
        val cached = cache[coord]
        return if(cached!=null)
            cached
        else {
            val matches = regex.matches(coord)
            cache[coord] = matches
            matches
        }
    }

    private inline fun Regex.matches(coord: MavenCoordinate) = matches(coord.groupId)
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy