Docker Compose Validator — Kotlin source
Validate a compose file in the browser: image or build per service, port syntax and ranges, environment shape, volumes, and the depends_on graph with cycle detection. Runs locally with a shareable link.
This is the Kotlin implementation — the same logic the interactive tool runs, in a shareable, citable form.
// compose-validator — structural checks for a Docker Compose file. Kotlin port
// (canonical TS: src/lib/compose-validator.ts; Go twin: cli/compose-validator).
// Checks: root/services mappings, per-service image or build, port syntax
// ("8080", "80:8080", "127.0.0.1:80:8080", "6053:53/udp"), environment shape
// (mapping or KEY=value list), volumes lists, depends_on references and
// acyclicity — same rules, paths and message texts as the TS contract. Kotlin's
// stdlib has no YAML parser, so, like every port in this set, a minimal
// hand-rolled parser covers the compose subset: block mappings/sequences,
// single-line flow collections, quoted and plain scalars, comments.
// Anchors/aliases/merge keys, block scalars (| >), multi-line plain scalars
// and multi-document streams are outside the subset. Never throws out of the
// entry point — parse errors travel in Result.error. The document tree keeps
// key order with LinkedHashMap.
import java.util.LinkedHashMap
/** One structural finding at one YAML path (TS ComposeIssue). */
class ComposeIssue(val path: String, val message: String)
/** TS ComposeValidateResult: error is null unless parsing failed. */
class ComposeValidateResult(val valid: Boolean, val issues: List<ComposeIssue>, val error: String?)
private class Line(val indent: Int, val body: String)
private val INT_RE = Regex("[-+]?[0-9]+")
private val FLOAT_RE = Regex("[-+]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][-+]?[0-9]+)?")
/** Core-schema resolution of a plain scalar: null/bool/Long/Double/String. */
private fun plainScalar(t: String): Any? = when (t) {
"", "~", "null", "Null", "NULL" -> null
"true", "True", "TRUE" -> true
"false", "False", "FALSE" -> false
else -> when {
INT_RE.matches(t) -> t.toLongOrNull() ?: t.toDouble()
FLOAT_RE.matches(t) -> t.toDouble()
else -> t
}
}
private fun ltrim(s: String): String = s.dropWhile { it == ' ' }
private fun rtrim(s: String): String = s.dropLastWhile { it == ' ' }
/** Quoted scalar at s[i]; returns (value, next index). "..." honors
* escapes, '...' doubles the quote. */
private fun quotedAt(s: String, iIn: Int): Pair<String, Int> {
val q = s[iIn]
var i = iIn + 1
val out = StringBuilder()
while (i < s.length) {
val ch = s[i]
if (q == '"' && ch == '\\') {
val nxt = if (i + 1 < s.length) s[i + 1] else '\u0000'
out.append(
when (nxt) {
'n' -> '\n'
't' -> '\t'
'r' -> '\r'
else -> nxt
}
)
i += 2
} else if (ch == q) {
if (q == '\'' && i + 1 < s.length && s[i + 1] == '\'') { out.append('\''); i += 2 }
else return out.toString() to i + 1
} else { out.append(ch); i += 1 }
}
throw IllegalStateException("Invalid YAML: unterminated quoted scalar")
}
/** One flow node at s[i]; returns (value, next index). */
private fun flowAt(s: String, iIn: Int): Pair<Any?, Int> {
var i = iIn
while (i < s.length && s[i] == ' ') i += 1
if (i < s.length && s[i] == '[') {
val out = ArrayList<Any?>()
i += 1
while (true) {
while (i < s.length && s[i] == ' ') i += 1
if (i >= s.length) throw IllegalStateException("Invalid YAML: unterminated flow sequence")
if (s[i] == ']') return out to i + 1
val (v, next) = flowAt(s, i)
out.add(v)
i = next
while (i < s.length && (s[i] == ' ' || s[i] == ',')) i += 1
}
}
if (i < s.length && s[i] == '{') {
val out = LinkedHashMap<String, Any?>()
i += 1
while (true) {
while (i < s.length && s[i] == ' ') i += 1
if (i >= s.length) throw IllegalStateException("Invalid YAML: unterminated flow mapping")
if (s[i] == '}') return out to i + 1
val k: String
if (s[i] == '"' || s[i] == '\'') {
val (key, next) = quotedAt(s, i)
k = key
i = next
} else {
var j = i
while (j < s.length && s[j] != ':' && s[j] != ',' && s[j] != '}') j += 1
if (j >= s.length || s[j] != ':') {
throw IllegalStateException("Invalid YAML: flow mapping entry without a colon")
}
k = s.substring(i, j).trim()
i = j + 1
}
while (i < s.length && s[i] == ' ') i += 1
var v: Any? = null
if (i < s.length && s[i] != ',' && s[i] != '}') {
val (value, next) = flowAt(s, i)
v = value
i = next
}
out[k] = v
while (i < s.length && (s[i] == ' ' || s[i] == ',')) i += 1
}
}
if (i < s.length && (s[i] == '"' || s[i] == '\'')) return quotedAt(s, i)
var j = i
while (j < s.length && s[j] != ',' && s[j] != ']' && s[j] != '}') j += 1
return plainScalar(s.substring(i, j).trim()) to j
}
/** `key: rest` split; null when the line is not a mapping entry. */
private fun keySplit(s: String): Pair<String, String>? {
if (s.isNotEmpty() && (s[0] == '"' || s[0] == '\'')) {
val (key, j) = try {
quotedAt(s, 0)
} catch (e: IllegalStateException) {
return null
}
val rest = ltrim(s.substring(j))
return if (rest.startsWith(":")) key to rest.substring(1) else null
}
for (j in s.indices) {
if (s[j] == ':' && (j + 1 == s.length || s[j + 1] == ' ')) {
return rtrim(s.substring(0, j)) to s.substring(j + 1)
}
}
return null
}
private fun contentLines(text: String): MutableList<Line> {
val out = mutableListOf<Line>()
for (raw in text.split("\n")) {
val crlf = if (raw.endsWith("\r")) raw.dropLast(1) else raw
val indented = ltrim(crlf)
val indent = crlf.length - indented.length
val body = rtrim(indented)
if (body.isEmpty() || body.startsWith("#") || body.startsWith("%") || body == "---") continue
if (crlf.substring(0, indent).contains('\t')) {
throw IllegalStateException("Invalid YAML: tab in indentation")
}
out.add(Line(indent, body))
}
return out
}
private fun isItem(s: String): Boolean = s == "-" || s.startsWith("- ")
/** The node whose first line is ls[i] at the given indent; (value, next). */
private fun blockAt(ls: MutableList<Line>, iIn: Int, indent: Int): Pair<Any?, Int> {
var i = iIn
if (isItem(ls[i].body)) {
val out = ArrayList<Any?>()
while (i < ls.size && ls[i].indent == indent && isItem(ls[i].body)) {
val content = if (ls[i].body.length > 2) ls[i].body.substring(2) else ""
val v: Any?
if (content.isBlank() || ltrim(content).startsWith("#")) {
i += 1
if (i < ls.size && ls[i].indent > indent) {
val (value, next) = blockAt(ls, i, ls[i].indent)
v = value
i = next
} else v = null
} else {
ls[i] = Line(indent + 2, content)
val (value, next) = blockAt(ls, i, indent + 2)
v = value
i = next
}
out.add(v)
}
return out to i
}
if (keySplit(ls[i].body) == null) return inlineValue(ls[i].body) to i + 1
val out = LinkedHashMap<String, Any?>()
while (i < ls.size && ls[i].indent == indent && !isItem(ls[i].body) && keySplit(ls[i].body) != null) {
val (key, rest0) = keySplit(ls[i].body)!!
val rest = rest0.trim()
i += 1
when {
rest.isNotEmpty() -> out[key] = inlineValue(rest)
i < ls.size && ls[i].indent > indent -> {
val (value, next) = blockAt(ls, i, ls[i].indent)
out[key] = value
i = next
}
i < ls.size && ls[i].indent == indent && isItem(ls[i].body) -> {
val (value, next) = blockAt(ls, i, indent)
out[key] = value
i = next
}
else -> out[key] = null
}
}
return out to i
}
/** The value part of `key: value` — flow, quoted, or plain (comment cut). */
private fun inlineValue(rest: String): Any? {
val c0 = if (rest.isEmpty()) '\u0000' else rest[0]
if (c0 == '[' || c0 == '{') {
val (v, j) = flowAt(rest, 0)
if (rest.substring(j).replace(" ", "").replace("#", "").isNotEmpty()) {
throw IllegalStateException("Invalid YAML: trailing content after flow value")
}
return v
}
if (c0 == '"' || c0 == '\'') {
val (v, j) = quotedAt(rest, 0)
if (rest.substring(j).replace(" ", "").replace("#", "").isNotEmpty()) {
throw IllegalStateException("Invalid YAML: trailing content after quoted value")
}
return v
}
val cut = rest.indexOf(" #")
return plainScalar(rtrim(if (cut >= 0) rest.substring(0, cut) else rest).trim())
}
/** The minimal parser: text → tree (LinkedHashMaps keep document order). */
fun parseYaml(text: String): Any? {
val ls = contentLines(text)
if (ls.isEmpty()) return null
val (v, i) = blockAt(ls, 0, ls[0].indent)
if (i != ls.size) throw IllegalStateException("Invalid YAML: inconsistent indentation")
return v
}
private fun isMap(v: Any?): Boolean = v is Map<*, *>
/** JavaScript String(number) for the values the messages can hit. */
private fun numStr(v: Any?): String = when (v) {
is Long -> v.toString()
is Double -> when {
!v.isFinite() -> "null"
v == Math.rint(v) && Math.abs(v) < 1e21 -> v.toLong().toString()
else -> v.toString()
}
else -> throw IllegalArgumentException()
}
/** TS String(value) form for depends_on coercion and messages. */
private fun tsStr(v: Any?): String = when (v) {
null -> "null"
is Boolean -> v.toString()
is Long, is Double -> numStr(v)
is String -> v
is List<*> -> v.joinToString(",") { tsStr(it) }
else -> "[object Object]"
}
/** One ports entry; an issue string or null. "8080", "80:8080",
* "127.0.0.1:80:8080", "::1:8080:80", "6053:53/udp" all pass. */
fun portIssue(entry: Any?): String? = when (entry) {
is Long -> if (entry < 0 || entry > 65535) "port $entry out of range 0-65535" else null
is Double ->
if (!entry.isFinite() || entry != Math.rint(entry)) "port must be a string or integer"
else if (entry < 0 || entry > 65535) "port " + numStr(entry) + " out of range 0-65535"
else null
is String -> {
val slash = entry.indexOf('/')
val proto = if (slash >= 0) entry.substring(slash + 1) else ""
if (proto.isNotEmpty() && proto != "tcp" && proto != "udp") {
"unknown protocol \"$proto\" (use tcp or udp)"
} else {
val body = if (proto.isEmpty()) entry else entry.substring(0, slash)
val parts = body.split(":")
// Host forms (localhost, IPv6 like ::1) carry non-numeric parts anywhere.
if (parts.any { !Regex("[0-9]+").matches(it) }) null
else if (parts.size > 3) "port must have 1-3 colon-separated parts"
else parts.firstOrNull { (it.toDoubleOrNull() ?: 0.0) > 65535 }
?.let { "port $it out of range 0-65535" }
}
}
else -> "port must be a string or integer" // Boolean, null, maps, lists
}
private fun scalarOk(v: Any?): Boolean =
v == null || v is String || v is Boolean || v is Long || v is Double
private fun depNames(raw: Any?, stringOnly: Boolean): List<String> = when (raw) {
is String -> listOf(raw)
is List<*> -> if (stringOnly) raw.filterIsInstance<String>() else raw.map { tsStr(it) }
is Map<*, *> -> raw.keys.filterIsInstance<String>()
else -> emptyList()
}
/** Walk the document; append issues in TS order (root, services, per-service
* in document order, then depends_on cycle detection). */
fun check(root: Any?, out: MutableList<ComposeIssue>) {
fun push(path: String, message: String) = out.add(ComposeIssue(path, message))
if (!isMap(root)) {
push("$", "compose root must be a mapping")
return
}
@Suppress("UNCHECKED_CAST")
val services = (root as Map<String, Any?>)["services"]
if (!isMap(services)) {
push("$.services", "missing or invalid \"services\" mapping")
return
}
@Suppress("UNCHECKED_CAST")
val svcMap = services as Map<String, Any?>
val ids = svcMap.keys.toList()
if (ids.isEmpty()) push("$.services", "services must not be empty")
for (id in ids) {
val svc = svcMap[id]
val at = "$.services.$id"
if (!isMap(svc)) {
push(at, "service must be a mapping")
continue
}
@Suppress("UNCHECKED_CAST")
val sm = svc as Map<String, Any?>
if (!sm.containsKey("image") && !sm.containsKey("build")) push(at, "service needs image or build")
if (sm.containsKey("ports")) {
val ports = sm["ports"]
if (ports !is List<*>) push("$at.ports", "ports must be a list")
else ports.forEachIndexed { i, p ->
portIssue(p)?.let { push("$at.ports[$i]", it) }
}
}
if (sm.containsKey("environment")) {
val env = sm["environment"]
when {
isMap(env) -> {
@Suppress("UNCHECKED_CAST")
val em = env as Map<String, Any?>
for ((k, v) in em) {
if (!scalarOk(v)) push("$at.environment.$k", "environment values must be scalars")
}
}
env is List<*> -> env.forEachIndexed { i, e ->
if (e !is String || !Regex("(?s)[^=]+=.*").matches(e)) {
push("$at.environment[$i]", "list environment entries must look like KEY=value")
}
}
else -> push("$at.environment", "environment must be a mapping or a list")
}
}
if (sm.containsKey("volumes") && sm["volumes"] !is List<*>) {
push("$at.volumes", "volumes must be a list")
}
if (sm.containsKey("depends_on")) {
val dep = sm["depends_on"]
if (dep !is List<*> && dep !is String && !isMap(dep)) {
push("$at.depends_on", "depends_on must be a string, list or mapping")
} else {
val names = when {
isMap(dep) -> (dep as Map<*, *>).keys.filterIsInstance<String>()
dep is List<*> -> dep.map { tsStr(it) }
else -> listOf(dep as String)
}
names.forEachIndexed { i, n ->
if (!svcMap.containsKey(n)) push("$at.depends_on[$i]", "unknown service \"$n\"")
}
}
}
}
// depends_on cycle detection (map-form conditions do not affect the graph).
val color = HashMap<String, Int>()
fun visit(sid: String, stack: List<String>) {
when (color[sid]) {
2 -> return
1 -> {
val chain = stack.drop(stack.indexOf(sid)) + sid
push("$.services", "depends_on cycle: " + chain.joinToString(" -> "))
return
}
}
color[sid] = 1
val svc = svcMap[sid]
if (isMap(svc) && (svc as Map<*, *>).containsKey("depends_on")) {
for (n in depNames(svc["depends_on"], stringOnly = true)) {
if (svcMap.containsKey(n)) visit(n, stack + sid)
}
}
color[sid] = 2
}
for (id in ids) visit(id, emptyList())
}
/** Validate a Docker Compose file. */
fun validateCompose(raw: String): ComposeValidateResult {
if (raw.isBlank()) {
return ComposeValidateResult(false, emptyList(), "A compose document is required")
}
val root = try {
parseYaml(raw)
} catch (e: IllegalStateException) {
return ComposeValidateResult(false, emptyList(), e.message)
}
val issues = mutableListOf<ComposeIssue>()
check(root, issues)
return if (issues.isEmpty()) ComposeValidateResult(true, emptyList(), null)
else ComposeValidateResult(false, issues, null)
}
fun main() {
val ok = validateCompose("services:\n web:\n image: nginx:1.25\n ports:\n - \"8080:80\"\n - 6053:53/udp\n db:\n image: postgres:16\n depends_on: web")
println("valid: " + ok.valid) // valid: true
val bad = validateCompose("services:\n web:\n image: nginx\n ports: [\"99999\"]")
bad.issues.forEach { println(it.path + ": " + it.message) }
println(validateCompose("services:\n a:\n image: x\n depends_on: b\n b:\n image: y\n depends_on: a").issues[0].message)
println(validateCompose(" ").error) // A compose document is required
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →