fun readRuleFromFile()

in bunch-cli/src/main/kotlin/org/jetbrains/bunches/bunchFile.kt [9:36]


fun readRuleFromFile(endSuffix: String, path: String): String {
    val file = File(path, BUNCH_FILE_NAME)
    if (!file.exists()) {
        throw BunchException(
            "Can't build rule for restore branch from '$endSuffix'. File '${file.canonicalPath}' doesn't exist"
        )
    }

    val branchRules = file.readLines().map { it.trim() }.filter { it.isNotEmpty() }

    val currentBranchSuffix = branchRules.firstOrNull()
    if (currentBranchSuffix == null) {
        throw BunchException("First line in '${file.canonicalPath}' should contain current branch name")
    }

    if (currentBranchSuffix == endSuffix) {
        return endSuffix
    }

    val requestedRule = branchRules.find { it == endSuffix || it.startsWith(endSuffix + "_") }
    if (requestedRule == null) {
        throw BunchException("Can't find rule for '$endSuffix' in file '${file.canonicalPath}'")
    }

    val ruleTargetToCurrent = (requestedRule + "_$currentBranchSuffix").split("_")

    return ruleTargetToCurrent.reversed().joinToString(separator = "_")
}