Skip to content

Docker Compose Validator — Swift 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 Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.

// compose-validator — structural checks for a Docker Compose file. Swift 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.
// Foundation 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 crashes on
// malformed input; parse errors travel in Result.error (nil mirrors TS null).
import Foundation

/// One structural finding at one YAML path (TS ComposeIssue).
struct ComposeIssue {
    let path: String
    let message: String
}

/// TS ComposeValidateResult: error is nil unless parsing failed.
struct ComposeValidateResult {
    let valid: Bool
    let issues: [ComposeIssue]
    let error: String?
}

/// One parsed YAML value in document order (maps keep key order).
indirect enum YNode {
    case null
    case bool(Bool)
    case int(Int)
    case double(Double)
    case string(String)
    case seq([YNode])
    case map([(String, YNode)])
}

struct YamlError: Error { let message: String }

private func plainScalar(_ t: String) -> YNode {
    switch t {
    case "", "~", "null", "Null", "NULL": return .null
    case "true", "True", "TRUE": return .bool(true)
    case "false", "False", "FALSE": return .bool(false)
    default: break
    }
    if t.range(of: "^[-+]?[0-9]+$", options: .regularExpression) != nil {
        if let n = Int64(t) { return .int(Int(n)) }
        return .double(Double(t) ?? 0)
    }
    if t.range(of: "^[-+]?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][-+]?[0-9]+)?$",
               options: .regularExpression) != nil {
        return .double(Double(t) ?? 0)
    }
    return .string(t)
}

/// Quoted scalar at s[i]; returns (value, next index). "..." honors escapes,
/// '...' doubles the quote.
private func quotedAt(_ s: [Character], _ i0: Int) throws -> (String, Int) {
    let q = s[i0]
    var i = i0 + 1
    var out = ""
    while i < s.count {
        let ch = s[i]
        if q == "\"" && ch == "\\" {
            let nxt = i + 1 < s.count ? s[i + 1] : Character("\0")
            switch nxt {
            case "n": out.append("\n")
            case "t": out.append("\t")
            case "r": out.append("\r")
            default: out.append(nxt)
            }
            i += 2
        } else if ch == q {
            if q == "'" && i + 1 < s.count && s[i + 1] == "'" { out.append("'"); i += 2 }
            else { return (out, i + 1) }
        } else {
            out.append(ch)
            i += 1
        }
    }
    throw YamlError(message: "Invalid YAML: unterminated quoted scalar")
}

/// One flow node at s[i]; returns (value, next index).
private func flowAt(_ s: [Character], _ i0: Int) throws -> (YNode, Int) {
    var i = i0
    while i < s.count && s[i] == " " { i += 1 }
    if i < s.count && s[i] == "[" {
        var out: [YNode] = []
        i += 1
        while true {
            while i < s.count && s[i] == " " { i += 1 }
            if i >= s.count { throw YamlError(message: "Invalid YAML: unterminated flow sequence") }
            if s[i] == "]" { return (.seq(out), i + 1) }
            let (v, next) = try flowAt(s, i)
            out.append(v)
            i = next
            while i < s.count && (s[i] == " " || s[i] == ",") { i += 1 }
        }
    }
    if i < s.count && s[i] == "{" {
        var out: [(String, YNode)] = []
        i += 1
        while true {
            while i < s.count && s[i] == " " { i += 1 }
            if i >= s.count { throw YamlError(message: "Invalid YAML: unterminated flow mapping") }
            if s[i] == "}" { return (.map(out), i + 1) }
            let k: String
            if s[i] == "\"" || s[i] == "'" {
                (k, i) = try quotedAt(s, i)
            } else {
                var j = i
                while j < s.count && s[j] != ":" && s[j] != "," && s[j] != "}" { j += 1 }
                if j >= s.count || s[j] != ":" {
                    throw YamlError(message: "Invalid YAML: flow mapping entry without a colon")
                }
                k = String(s[i..<j]).trimmingCharacters(in: .whitespaces)
                i = j + 1
            }
            while i < s.count && s[i] == " " { i += 1 }
            var v = YNode.null
            if i < s.count && s[i] != "," && s[i] != "}" {
                (v, i) = try flowAt(s, i)
            }
            out.append((k, v))
            while i < s.count && (s[i] == " " || s[i] == ",") { i += 1 }
        }
    }
    if i < s.count && (s[i] == "\"" || s[i] == "'") {
        let (v, next) = try quotedAt(s, i)
        return (.string(v), next)
    }
    var j = i
    while j < s.count && s[j] != "," && s[j] != "]" && s[j] != "}" { j += 1 }
    let t = String(s[i..<j]).trimmingCharacters(in: .whitespaces)
    return (plainScalar(t), j)
}

/// `key: rest` split; nil when the line is not a mapping entry. The first
/// colon followed by a space (or ending the line) wins; quoted keys first.
private func keySplit(_ s: String) -> (String, String)? {
    let sc = Array(s)
    if let c0 = sc.first, c0 == "\"" || c0 == "'" {
        guard let (key, j) = try? quotedAt(sc, 0) else { return nil }
        let rest = sc[j...].drop(while: { $0 == " " })
        guard rest.first == ":" else { return nil }
        return (key, String(rest.dropFirst()))
    }
    for j in sc.indices {
        if sc[j] == ":" && (j + 1 == sc.count || sc[j + 1] == " ") {
            let key = String(sc[..<j].reversed().drop(while: { $0 == " " }).reversed())
            return (key, String(sc[(j + 1)...]))
        }
    }
    return nil
}

/// Content lines as (indent, body): blanks, comments, %directives and a ---
/// marker dropped; tab indentation rejected.
private func contentLines(_ text: String) throws -> [(Int, String)] {
    var out: [(Int, String)] = []
    for raw in text.components(separatedBy: "\n") {
        var crlf = Substring(raw)
        if crlf.hasSuffix("\r") { crlf = crlf.dropLast() }
        let indented = crlf.drop(while: { $0 == " " })
        let indent = crlf.count - indented.count
        let body = indented.reversed().drop(while: { $0 == " " }).reversed()
        let bs = String(body)
        if bs.isEmpty || bs.hasPrefix("#") || bs.hasPrefix("%") || bs == "---" { continue }
        if crlf.prefix(indent).contains("\t") {
            throw YamlError(message: "Invalid YAML: tab in indentation")
        }
        out.append((indent, bs))
    }
    return out
}

private func isItem(_ s: String) -> Bool { s == "-" || s.hasPrefix("- ") }

/// The node whose first line is ls[i] at the given indent; (value, next).
private func blockAt(_ ls: inout [(Int, String)], _ i0: Int, _ indent: Int) throws -> (YNode, Int) {
    var i = i0
    if isItem(ls[i].1) {
        var out: [YNode] = []
        while i < ls.count && ls[i].0 == indent && isItem(ls[i].1) {
            let content = String(ls[i].1.dropFirst(2))
            var v: YNode
            if content.trimmingCharacters(in: .whitespaces).isEmpty
                || content.drop(while: { $0 == " " }).first == "#" {
                i += 1
                if i < ls.count && ls[i].0 > indent {
                    (v, i) = try blockAt(&ls, i, ls[i].0)
                } else {
                    v = .null
                }
            } else {
                ls[i] = (indent + 2, content)
                (v, i) = try blockAt(&ls, i, indent + 2)
            }
            out.append(v)
        }
        return (.seq(out), i)
    }
    if keySplit(ls[i].1) == nil {
        let v = try inlineValue(ls[i].1)
        return (v, i + 1)
    }
    var out: [(String, YNode)] = []
    while i < ls.count && ls[i].0 == indent && !isItem(ls[i].1) && keySplit(ls[i].1) != nil {
        let (key, rest0) = keySplit(ls[i].1)!
        let rest = rest0.trimmingCharacters(in: .whitespaces)
        i += 1
        if !rest.isEmpty {
            out.append((key, try inlineValue(rest)))
        } else if i < ls.count && ls[i].0 > indent {
            let (v, ni) = try blockAt(&ls, i, ls[i].0)
            out.append((key, v))
            i = ni
        } else if i < ls.count && ls[i].0 == indent && isItem(ls[i].1) {
            let (v, ni) = try blockAt(&ls, i, indent)
            out.append((key, v))
            i = ni
        } else {
            out.append((key, .null))
        }
    }
    return (.map(out), i)
}

/// The value part of `key: value` — flow, quoted, or plain (comment cut).
private func inlineValue(_ rest: String) throws -> YNode {
    let sc = Array(rest)
    let c0 = sc.first ?? "\0"
    if c0 == "[" || c0 == "{" {
        let (v, j) = try flowAt(sc, 0)
        if sc[j...].contains(where: { $0 != " " && $0 != "#" }) {
            throw YamlError(message: "Invalid YAML: trailing content after flow value")
        }
        return v
    }
    if c0 == "\"" || c0 == "'" {
        let (v, j) = try quotedAt(sc, 0)
        if sc[j...].contains(where: { $0 != " " && $0 != "#" }) {
            throw YamlError(message: "Invalid YAML: trailing content after quoted value")
        }
        return v
    }
    var t = rest
    if let cut = rest.range(of: " #") { t = String(rest[..<cut.lowerBound]) }
    return plainScalar(t.trimmingCharacters(in: .whitespaces))
}

/// The minimal parser: text → tree (map arrays keep document order).
func parseYaml(_ text: String) throws -> YNode {
    var ls = try contentLines(text)
    if ls.isEmpty { return .null }
    let (v, i) = try blockAt(&ls, 0, ls[0].0)
    if i != ls.count { throw YamlError(message: "Invalid YAML: inconsistent indentation") }
    return v
}

private func isMap(_ v: YNode) -> Bool {
    if case .map = v { return true }
    return false
}

private func mapGet(_ v: YNode, _ key: String) -> YNode? {
    if case .map(let m) = v { return m.first(where: { $0.0 == key })?.1 }
    return nil
}

/// JavaScript String(number) for the values the messages can hit.
private func numText(_ f: Double) -> String {
    if !f.isFinite { return "null" }
    if f == f.rounded(.towardZero) && abs(f) < 1e21 { return String(Int64(f)) }
    return String(f)
}

/// TS String(value) form for depends_on coercion and messages.
private func tsStr(_ v: YNode) -> String {
    switch v {
    case .null: return "null"
    case .bool(true): return "true"
    case .bool(false): return "false"
    case .int(let n): return String(n)
    case .double(let f): return numText(f)
    case .string(let s): return s
    case .seq(let items): return items.map(tsStr).joined(separator: ",")
    case .map: return "[object Object]"
    }
}

/// /^[^=]+=./s — at least one non-'=' char, then '=', then anything.
private func envKvOk(_ s: String) -> Bool {
    guard let p = s.firstIndex(of: "=") else { return false }
    return s.distance(from: s.startIndex, to: p) >= 1
}

/// One ports entry; an issue string or nil. "8080", "80:8080",
/// "127.0.0.1:80:8080", "::1:8080:80", "6053:53/udp" all pass.
func portIssue(_ entry: YNode) -> String? {
    switch entry {
    case .int(let n):
        return (n < 0 || n > 65535) ? "port \(n) out of range 0-65535" : nil
    case .double(let f):
        if !f.isFinite || f != f.rounded(.towardZero) { return "port must be a string or integer" }
        return (f < 0 || f > 65535) ? "port \(numText(f)) out of range 0-65535" : nil
    case .string(let s):
        let slash = s.firstIndex(of: "/")
        let proto = slash.map { String(s[s.index(after: $0)...]) } ?? ""
        if !proto.isEmpty && proto != "tcp" && proto != "udp" {
            return "unknown protocol \"\(proto)\" (use tcp or udp)"
        }
        let body = proto.isEmpty ? s : String(s[s.startIndex..<slash!])
        let parts = body.components(separatedBy: ":")
        // Host forms (localhost, IPv6 like ::1) carry non-numeric parts anywhere.
        if !parts.allSatisfy({ $0.range(of: "^[0-9]+$", options: .regularExpression) != nil }) {
            return nil
        }
        if parts.count > 3 { return "port must have 1-3 colon-separated parts" }
        for p in parts {
            let n = Double(p) ?? 0
            if n < 0 || n > 65535 { return "port \(p) out of range 0-65535" }
        }
        return nil
    default:
        return "port must be a string or integer" // bool, null, maps, lists
    }
}

private func scalarOk(_ v: YNode) -> Bool {
    switch v {
    case .null, .bool, .int, .double, .string: return true
    default: return false
    }
}

/// Walk the document; append issues in TS order (root, services, per-service
/// in document order, then depends_on cycle detection).
func check(_ root: YNode, _ out: inout [ComposeIssue]) {
    func push(_ path: String, _ message: String) { out.append(ComposeIssue(path: path, message: message)) }
    guard case .map(let rootMap) = root else {
        push("$", "compose root must be a mapping")
        return
    }
    guard let servicesNode = rootMap.first(where: { $0.0 == "services" })?.1,
          case .map(let services) = servicesNode else {
        push("$.services", "missing or invalid \"services\" mapping")
        return
    }
    let ids = services.map { $0.0 }
    if ids.isEmpty { push("$.services", "services must not be empty") }
    for id in ids {
        let svc = services.first(where: { $0.0 == id })?.1 ?? .null
        let at = "$.services.\(id)"
        guard case .map(let sm) = svc else {
            push(at, "service must be a mapping")
            continue
        }
        let has = { (k: String) in sm.contains(where: { $0.0 == k }) }
        if !has("image") && !has("build") { push(at, "service needs image or build") }
        if has("ports") {
            switch mapGet(svc, "ports") ?? .null {
            case .seq(let items):
                for (i, p) in items.enumerated() {
                    if let msg = portIssue(p) { push("\(at).ports[\(i)]", msg) }
                }
            default:
                push("\(at).ports", "ports must be a list")
            }
        }
        if has("environment") {
            switch mapGet(svc, "environment") ?? .null {
            case .map(let m):
                for (k, v) in m where !scalarOk(v) {
                    push("\(at).environment.\(k)", "environment values must be scalars")
                }
            case .seq(let items):
                for (i, e) in items.enumerated() {
                    var ok = false
                    if case .string(let s) = e { ok = envKvOk(s) }
                    if !ok {
                        push("\(at).environment[\(i)]", "list environment entries must look like KEY=value")
                    }
                }
            default:
                push("\(at).environment", "environment must be a mapping or a list")
            }
        }
        if has("volumes") {
            if case .seq = mapGet(svc, "volumes") ?? .null {} else {
                push("\(at).volumes", "volumes must be a list")
            }
        }
        if has("depends_on") {
            let dep = mapGet(svc, "depends_on") ?? .null
            var ok = false
            var names: [String] = []
            switch dep {
            case .map(let m):
                ok = true
                names = m.map { $0.0 }
            case .seq(let items):
                ok = true
                names = items.map(tsStr)
            case .string(let s):
                ok = true
                names = [s]
            default:
                break
            }
            if !ok {
                push("\(at).depends_on", "depends_on must be a string, list or mapping")
            } else {
                for (i, n) in names.enumerated() where !services.contains(where: { $0.0 == n }) {
                    push("\(at).depends_on[\(i)]", "unknown service \"\(n)\"")
                }
            }
        }
    }

    // depends_on cycle detection (map-form conditions do not affect the graph).
    var color: [String: Int] = [:]
    func visit(_ sid: String, _ stack: [String]) {
        let c = color[sid]
        if c == 2 { return }
        if c == 1 {
            let from = stack.firstIndex(of: sid) ?? 0
            let chain = Array(stack[from...]) + [sid]
            push("$.services", "depends_on cycle: " + chain.joined(separator: " -> "))
            return
        }
        color[sid] = 1
        if case .map(let sm) = services.first(where: { $0.0 == sid })?.1 ?? .null {
            if let raw = sm.first(where: { $0.0 == "depends_on" })?.1 {
                var names: [String] = []
                switch raw {
                case .string(let s): names = [s]
                case .seq(let items):
                    names = items.compactMap { e in
                        if case .string(let s) = e { return s }
                        return nil
                    }
                case .map(let m): names = m.map { $0.0 }
                default: break
                }
                for n in names where services.contains(where: { $0.0 == n }) {
                    visit(n, stack + [sid])
                }
            }
        }
        color[sid] = 2
    }
    for id in ids { visit(id, []) }
}

/// Validate a Docker Compose file.
func validateCompose(_ raw: String) -> ComposeValidateResult {
    if raw.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
        return ComposeValidateResult(valid: false, issues: [], error: "A compose document is required")
    }
    let root: YNode
    do {
        root = try parseYaml(raw)
    } catch let e as YamlError {
        return ComposeValidateResult(valid: false, issues: [], error: e.message)
    } catch {
        return ComposeValidateResult(valid: false, issues: [], error: "Invalid YAML")
    }
    var issues: [ComposeIssue] = []
    check(root, &issues)
    return issues.isEmpty
        ? ComposeValidateResult(valid: true, issues: [], error: nil)
        : ComposeValidateResult(valid: false, issues: issues, error: nil)
}

// Example:
// let ok = validateCompose("services:\n  web:\n    image: nginx:1.25\n    ports:\n      - \"8080:80\"\n  db:\n    image: postgres:16\n    depends_on: web")
// // ok.valid == true, ok.error == nil
// let bad = validateCompose("services:\n  web:\n    image: nginx\n    ports: [\"99999\"]")
// // bad.issues[0].path == "$.services.web.ports[0]"
// // bad.issues[0].message == "port 99999 out of range 0-65535"
// validateCompose("services:\n  a:\n    image: x\n    depends_on: b\n  b:\n    image: y\n    depends_on: a").issues[0].message
// → "depends_on cycle: a -> b -> a"

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 →