name.remal.gradle_plugins.dsl.utils.canonizeText.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.nullIfEmpty
private val severalNewLinesRegex = Regex("\n{3,}")
fun canonizeText(value: String?, tabSize: Int = 4): String? {
if (value == null) return null
var result = value
.replace("\r", "")
.replace("\t", " ".repeat(tabSize))
.trim('\n')
.nullIfEmpty()
if (result == null) return null
result = result.splitToSequence('\n')
.map(String::trimEnd)
.toMutableList()
.also { lines ->
var minIndent = -1
lines.forEach { line ->
if (line.isNotEmpty()) {
if (minIndent < 0) {
minIndent = line.indexOfFirst { it != ' ' }
} else {
minIndent = Math.min(minIndent, line.indexOfFirst { it != ' ' })
}
}
}
if (minIndent > 0) {
lines.forEachIndexed { index, line ->
if (line.isNotEmpty()) {
lines[index] = line.substring(minIndent)
}
}
}
}
.joinToString("\n")
.nullIfEmpty()
if (result == null) return null
return result.replace(severalNewLinesRegex, "\n\n")
}