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

name.remal.gradle_plugins.dsl.utils.PathMatcher.kt Maven / Gradle / Ivy

There is a newer version: 1.9.2
Show newest version
package name.remal.gradle_plugins.dsl.utils

import name.remal.escapeRegex
import org.gradle.api.file.RelativePath
import kotlin.text.RegexOption.IGNORE_CASE

data class PathMatcher private constructor(private val caseSensitive: Boolean, private val pattern: String) {

    @JvmOverloads
    constructor(pattern: String, caseSensitive: Boolean = true) : this(
        caseSensitive,
        canonizePath(pattern)
            .let { if (it.endsWith("/")) it + "**" else it }
    )

    private val regex: Regex = run {
        val regex = escapeRegex(pattern)
            .let {
                if (it.startsWith("\\*\\*/")) {
                    "(?:[^/]+/)*" + it.substring(5)
                } else {
                    it
                }
            }
            .replace("/\\*\\*", "(?:/[^/]+)*")
            .replace("\\*", "[^/]*")
            .replace("\\?", "[^/]")
        val options = if (caseSensitive) emptySet() else setOf(IGNORE_CASE)
        Regex(regex, options)
    }

    fun matches(path: String) = regex.matches(canonizePath(path))

    companion object {
        private fun canonizePath(path: String) = path
            .replace('\\', '/')
            .replace(MULTIPLE_DELIMITERS_REGEX, "/")

        private val MULTIPLE_DELIMITERS_REGEX = Regex("/{2,}")
    }

}


fun PathMatcher.matches(relativePath: RelativePath) = matches(relativePath.toString())




© 2015 - 2024 Weber Informatics LLC | Privacy Policy