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

name.remal.gradle_plugins.dsl.utils.canonizeText.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.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")
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy