name.remal.gradle_plugins.dsl.utils.PathMatcher.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of gradle-plugins-kotlin-dsl Show documentation
Show all versions of gradle-plugins-kotlin-dsl Show documentation
Remal Gradle plugins: gradle-plugins-kotlin-dsl
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())