Docker Compose Validator — Ruby 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 Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.
# compose-validator — structural checks for a Docker Compose file. Ruby 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. Ruby's
# stdlib ships no YAML parser (psych is a gem dependency), 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 raises —
# parse errors travel in [:error].
module ComposeValidator
module_function
INT_RE = /\A[-+]?[0-9]+\z/.freeze
FLOAT_RE = /\A[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?\z/.freeze
def plain_scalar(t)
return nil if ['', '~', 'null', 'Null', 'NULL'].include?(t)
return true if t == 'true' || t == 'True' || t == 'TRUE'
return false if t == 'false' || t == 'False' || t == 'FALSE'
return t.to_i if t.match?(INT_RE)
return Float(t) if t.match?(FLOAT_RE)
t
end
# Quoted scalar at s[i]; returns [value, next index]. "..." honors
# escapes, '...' doubles the quote.
def quoted_at(s, i)
q = s[i]
i += 1
out = +''
while i < s.length
ch = s[i]
if q == '"' && ch == '\\'
nxt = s[i + 1] || ''
out << { 'n' => "\n", 't' => "\t", 'r' => "\r" }.fetch(nxt, nxt)
i += 2
elsif ch == q
if q == "'" && s[i + 1] == "'"
out << "'"
i += 2
else
return out, i + 1
end
else
out << ch
i += 1
end
end
raise 'unterminated quoted scalar'
end
# One flow node at s[i]; returns [value, next index].
def flow_at(s, i)
i += 1 while s[i] == ' '
if s[i] == '['
out = []
i += 1
loop do
i += 1 while s[i] == ' '
raise 'unterminated flow sequence' if i >= s.length
return out, i + 1 if s[i] == ']'
v, i = flow_at(s, i)
out << v
i += 1 while s[i] == ' ' || s[i] == ','
end
end
if s[i] == '{'
out = {}
i += 1
loop do
i += 1 while s[i] == ' '
raise 'unterminated flow mapping' if i >= s.length
return out, i + 1 if s[i] == '}'
if s[i] == '"' || s[i] == "'"
k, i = quoted_at(s, i)
else
j = i
j += 1 while j < s.length && !':,}'.include?(s[j])
raise 'flow mapping entry without a colon' unless s[j] == ':'
k = s[i...j].strip
i = j + 1
end
i += 1 while s[i] == ' '
v = nil
v, i = flow_at(s, i) unless s[i].nil? || s[i] == ',' || s[i] == '}'
out[k] = v
i += 1 while s[i] == ' ' || s[i] == ','
end
end
return quoted_at(s, i) if s[i] == '"' || s[i] == "'"
j = i
j += 1 while j < s.length && !',]}'.include?(s[j])
[plain_scalar(s[i...j].strip), j]
end
# `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.
def key_split(s)
if s.start_with?('"', "'")
begin
key, j = quoted_at(s, 0)
rescue RuntimeError
return nil
end
rest = s[j..].sub(/\A +/, '')
return rest.start_with?(':') ? [key, rest[1..]] : nil
end
s.length.times do |j|
if s[j] == ':' && (j + 1 == s.length || s[j + 1] == ' ')
return [s[0...j].sub(/ +\z/, ''), s[(j + 1)..]]
end
end
nil
end
def content_lines(text)
out = []
text.split("\n", -1).each do |raw|
crlf = raw.sub(/\r\z/, '')
indented = crlf.sub(/\A +/, '')
indent = crlf.length - indented.length
body = indented.sub(/ +\z/, '')
next if body == '' || body.start_with?('#', '%') || body == '---'
raise 'tab in indentation' if crlf[0, indent].include?("\t")
out << [indent, body]
end
out
end
def item_line?(s)
s == '-' || s.start_with?('- ')
end
# The node whose first line is ls[i] at the given indent; [value, next].
def block_at(ls, i, indent)
if item_line?(ls[i][1])
out = []
while i < ls.length && ls[i][0] == indent && item_line?(ls[i][1])
content = ls[i][1][2..] || ''
if content.strip == '' || content.lstrip.start_with?('#')
i += 1
if i < ls.length && ls[i][0] > indent
v, i = block_at(ls, i, ls[i][0])
else
v = nil
end
else
ls[i] = [indent + 2, content]
v, i = block_at(ls, i, indent + 2)
end
out << v
end
return out, i
end
return [inline_value(ls[i][1]), i + 1] if key_split(ls[i][1]).nil?
out = {}
while i < ls.length && ls[i][0] == indent && !item_line?(ls[i][1]) \
&& !(kv = key_split(ls[i][1])).nil?
key, rest = kv
rest = rest.strip
i += 1
if rest != ''
out[key] = inline_value(rest)
elsif i < ls.length && ls[i][0] > indent
out[key], i = block_at(ls, i, ls[i][0])
elsif i < ls.length && ls[i][0] == indent && item_line?(ls[i][1])
out[key], i = block_at(ls, i, indent)
else
out[key] = nil
end
end
[out, i]
end
# The value part of `key: value` — flow, quoted, or plain (comment cut).
def inline_value(rest)
if rest[0] == '[' || rest[0] == '{'
v, j = flow_at(rest, 0)
raise 'trailing content after flow value' unless rest[j..].gsub(/[ #]/, '') == ''
return v
end
if rest[0] == '"' || rest[0] == "'"
v, j = quoted_at(rest, 0)
raise 'trailing content after quoted value' unless rest[j..].gsub(/[ #]/, '') == ''
return v
end
cut = rest.index(' #')
plain_scalar((cut ? rest[0...cut] : rest).strip)
end
# The minimal parser: text → tree (Hashes keep document order).
def parse_yaml(text)
ls = content_lines(text)
return nil if ls.empty?
v, i = block_at(ls, 0, ls[0][0])
raise 'inconsistent indentation' unless i == ls.length
v
end
def map?(v)
v.is_a?(Hash)
end
# JavaScript String(number) for the floats the messages can hit.
def num_text(f)
return 'null' unless f.finite?
return f.to_i.to_s if f == f.floor && f.abs < 1e21
f.to_s
end
# TS String(value) form for depends_on coercion and messages.
def ts_str(v)
case v
when nil then 'null'
when true then 'true'
when false then 'false'
when Integer then v.to_s
when Float then num_text(v)
when String then v
when Array then v.map { |e| ts_str(e) }.join(',')
else '[object Object]'
end
end
# 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.
def port_issue(entry)
case entry
when Integer
return "port #{entry} out of range 0-65535" if entry.negative? || entry > 65_535
nil
when Float
return 'port must be a string or integer' if !entry.finite? || entry != entry.floor
return "port #{num_text(entry)} out of range 0-65535" if entry.negative? || entry > 65_535
nil
when String
slash = entry.index('/')
proto = slash ? entry[(slash + 1)..] : ''
return "unknown protocol \"#{proto}\" (use tcp or udp)" unless ['', 'tcp', 'udp'].include?(proto)
body = proto == '' ? entry : entry[0...slash]
parts = body.split(':')
return nil unless parts.all? { |p| p.match?(/\A[0-9]+\z/) }
return 'port must have 1-3 colon-separated parts' if parts.length > 3
parts.each { |p| return "port #{p} out of range 0-65535" if p.to_i > 65_535 }
nil
else
'port must be a string or integer'
end
end
# Walk the document; append issues in TS order (root, services, per-service
# in document order, then depends_on cycle detection).
def check(root, out)
push = ->(path, message) { out << { path: path, message: message } }
unless map?(root)
push.call('$', 'compose root must be a mapping')
return
end
services = root['services']
unless map?(services)
push.call('$.services', 'missing or invalid "services" mapping')
return
end
ids = services.keys
push.call('$.services', 'services must not be empty') if ids.empty?
ids.each do |sid|
svc = services[sid]
at = "$.services.#{sid}"
unless map?(svc)
push.call(at, 'service must be a mapping')
next
end
push.call(at, 'service needs image or build') unless svc.key?('image') || svc.key?('build')
if svc.key?('ports')
ports = svc['ports']
if !ports.is_a?(Array)
push.call("#{at}.ports", 'ports must be a list')
else
ports.each_with_index do |p, i|
msg = port_issue(p)
push.call("#{at}.ports[#{i}]", msg) if msg
end
end
end
if svc.key?('environment')
env = svc['environment']
if map?(env)
env.each do |k, v|
unless v.nil? || v == true || v == false || v.is_a?(String) || v.is_a?(Numeric)
push.call("#{at}.environment.#{k}", 'environment values must be scalars')
end
end
elsif env.is_a?(Array)
env.each_with_index do |e, i|
if !e.is_a?(String) || e !~ /\A[^=]+=.*\z/m
push.call("#{at}.environment[#{i}]", 'list environment entries must look like KEY=value')
end
end
else
push.call("#{at}.environment", 'environment must be a mapping or a list')
end
end
push.call("#{at}.volumes", 'volumes must be a list') if svc.key?('volumes') && !svc['volumes'].is_a?(Array)
next unless svc.key?('depends_on')
dep = svc['depends_on']
if !dep.is_a?(Array) && !dep.is_a?(String) && !map?(dep)
push.call("#{at}.depends_on", 'depends_on must be a string, list or mapping')
else
names = map?(dep) ? dep.keys : dep.is_a?(String) ? [dep] : dep.map { |e| ts_str(e) }
names.each_with_index do |n, i|
push.call("#{at}.depends_on[#{i}]", "unknown service \"#{n}\"") unless services.key?(n)
end
end
end
# depends_on cycle detection (map-form conditions do not affect the graph).
color = {}
visit = nil
visit = lambda do |sid, stack|
c = color[sid]
return if c == 2
if c == 1
chain = stack[stack.index(sid)..] + [sid]
push.call('$.services', 'depends_on cycle: ' + chain.join(' -> '))
return
end
color[sid] = 1
svc = services[sid]
if map?(svc) && svc.key?('depends_on')
raw = svc['depends_on']
names = if raw.is_a?(String)
[raw]
elsif raw.is_a?(Array)
raw.select { |e| e.is_a?(String) }
elsif map?(raw)
raw.keys
else
[]
end
names.each { |n| visit.call(n, stack + [sid]) if services.key?(n) }
end
color[sid] = 2
end
ids.each { |sid| visit.call(sid, []) }
end
# Validate a Docker Compose file → {valid:, issues:, error:}.
def validate_compose(raw)
return { valid: false, issues: [], error: 'A compose document is required' } if raw.strip.empty?
begin
root = parse_yaml(raw)
rescue RuntimeError => e
return { valid: false, issues: [], error: "Invalid YAML: #{e.message}" }
end
issues = []
check(root, issues)
{ valid: issues.empty?, issues: issues, error: nil }
end
end
# Example:
# ComposeValidator.validate_compose('services:\n web:\n image: nginx:1.25\n ports:\n - "8080:80"\n db:\n image: postgres:16\n depends_on: web')[:valid]
# → true
# ComposeValidator.validate_compose('services:\n web:\n image: nginx\n ports: ["99999"]')[:issues]
# → [{path: "$.services.web.ports[0]", message: "port 99999 out of range 0-65535"}]
# ComposeValidator.validate_compose('services:\n a:\n image: x\n depends_on: b\n b:\n image: y\n depends_on: a')[:issues]
# → [{path: "$.services", 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 →