de.gesellix.docker.compose.interpolation.ComposeInterpolator.kt Maven / Gradle / Ivy
package de.gesellix.docker.compose.interpolation
class ComposeInterpolator {
private val template = Template()
fun interpolate(composeContent: Map?>?>, environment: Map): Map?>> {
val result = hashMapOf?>>()
listOf("services", "networks", "volumes", "secrets", "configs").forEach { section ->
val sectionConfig = composeContent[section]
if (sectionConfig != null) {
result[section] = interpolateSection(sectionConfig, environment)
}
}
return result
}
private fun interpolateSection(config: Map?>, environment: Map): Map?> {
val result = hashMapOf?>()
config.forEach { (key, value) ->
if (value == null) {
result[key] = null
} else {
try {
result[key] = interpolateSectionItem(key, value, environment)
} catch (e: Exception) {
throw IllegalStateException("Invalid type for $key: ${value.javaClass} instead of ${result.javaClass}", e)
}
}
}
return result
}
private fun interpolateSectionItem(name: String, config: Map, environment: Map): Map {
val result = hashMapOf()
config.forEach { (key, value) ->
result[key] = recursiveInterpolate(value, environment)
// if err != nil {
// return nil, errors.Errorf(
// "Invalid interpolation format for %#v option in %s %#v: %#v. You may need to escape any $ with another $.",
// key, section, name, err.Template,
// )
// }
}
return result
}
private fun recursiveInterpolate(value: Any?, environment: Map): Any? {
when (value) {
null -> return null
is String -> return template.substitute(value, environment)
is Map<*, *> -> {
val interpolatedMap = hashMapOf()
value.forEach { (key, elem) ->
if (key != null) {
interpolatedMap[key] = recursiveInterpolate(elem, environment)
}
}
return interpolatedMap
}
is List<*> -> {
val interpolatedList = arrayListOf()
value.forEach { elem ->
interpolatedList.add(recursiveInterpolate(elem, environment))
}
return interpolatedList
}
else -> return value
}
}
}