Docker Compose Validator — C# 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 C# implementation — the same logic the interactive tool runs, in a shareable, citable form.
// compose-validator — structural checks for a Docker Compose file. C# 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. .NET's
// base class library 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. Key order is kept
// with OrderedDictionary (System.Collections.Specialized, in the BCL).
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
public class ComposeIssue
{
public string Path;
public string Message;
public ComposeIssue(string path, string message) { Path = path; Message = message; }
}
// TS ComposeValidateResult: Error is null unless parsing failed (TS: null).
public class ComposeValidateResult
{
public bool Valid;
public List<ComposeIssue> Issues;
public string Error;
public ComposeValidateResult(bool valid, List<ComposeIssue> issues, string error)
{
Valid = valid; Issues = issues; Error = error;
}
}
/// One content line: indent + body (blanks/comments/directives dropped).
internal class Line
{
internal int Indent;
internal string Body;
internal Line(int indent, string body) { Indent = indent; Body = body; }
}
public static class ComposeValidator
{
private static readonly Regex IntRe = new Regex(@"\A[-+]?[0-9]+\z");
private static readonly Regex FloatRe = new Regex(@"\A[-+]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][-+]?[0-9]+)?\z");
private static readonly Regex DigitsRe = new Regex(@"\A[0-9]+\z");
private static readonly Regex EnvKvRe = new Regex(@"(?s)\A[^=]+=.*\z");
/// Core-schema resolution of a plain scalar: null/bool/long/double/string.
private static object PlainScalar(string t)
{
switch (t)
{
case "": case "~": case "null": case "Null": case "NULL": return null;
case "true": case "True": case "TRUE": return true;
case "false": case "False": case "FALSE": return false;
default:
if (IntRe.IsMatch(t))
{
if (long.TryParse(t, out long n)) return n;
return double.Parse(t, CultureInfo.InvariantCulture);
}
if (FloatRe.IsMatch(t)) return double.Parse(t, CultureInfo.InvariantCulture);
return t;
}
}
private static string LTrim(string s)
{
int i = 0;
while (i < s.Length && s[i] == ' ') i += 1;
return s.Substring(i);
}
private static string RTrim(string s)
{
int e = s.Length;
while (e > 0 && s[e - 1] == ' ') e -= 1;
return s.Substring(0, e);
}
/// Quoted scalar at s[i]; "..." honors escapes, '...' doubles the quote.
private static string QuotedAt(string s, int i, out int next)
{
char q = s[i];
i += 1;
var outp = new StringBuilder();
while (i < s.Length)
{
char ch = s[i];
if (q == '"' && ch == '\\')
{
char nxt = i + 1 < s.Length ? s[i + 1] : '\0';
switch (nxt)
{
case 'n': outp.Append('\n'); break;
case 't': outp.Append('\t'); break;
case 'r': outp.Append('\r'); break;
default: outp.Append(nxt); break;
}
i += 2;
}
else if (ch == q)
{
if (q == '\'' && i + 1 < s.Length && s[i + 1] == '\'') { outp.Append('\''); i += 2; }
else { next = i + 1; return outp.ToString(); }
}
else { outp.Append(ch); i += 1; }
}
throw new InvalidOperationException("Invalid YAML: unterminated quoted scalar");
}
/// One flow node at s[i] (spaces already skipped); i is advanced past it.
private static object FlowAt(string s, ref int i)
{
while (i < s.Length && s[i] == ' ') i += 1;
if (i < s.Length && s[i] == '[')
{
var outp = new List<object>();
i += 1;
for (; ; )
{
while (i < s.Length && s[i] == ' ') i += 1;
if (i >= s.Length) throw new InvalidOperationException("Invalid YAML: unterminated flow sequence");
if (s[i] == ']') { i += 1; return outp; }
outp.Add(FlowAt(s, ref i));
while (i < s.Length && (s[i] == ' ' || s[i] == ',')) i += 1;
}
}
if (i < s.Length && s[i] == '{')
{
var outp = new OrderedDictionary();
i += 1;
for (; ; )
{
while (i < s.Length && s[i] == ' ') i += 1;
if (i >= s.Length) throw new InvalidOperationException("Invalid YAML: unterminated flow mapping");
if (s[i] == '}') { i += 1; return outp; }
string k;
if (s[i] == '"' || s[i] == '\'')
{
k = QuotedAt(s, i, out int ki);
i = ki;
}
else
{
int j = i;
while (j < s.Length && s[j] != ':' && s[j] != ',' && s[j] != '}') j += 1;
if (j >= s.Length || s[j] != ':') throw new InvalidOperationException("Invalid YAML: flow mapping entry without a colon");
k = s.Substring(i, j - i).Trim();
i = j + 1;
}
while (i < s.Length && s[i] == ' ') i += 1;
object v = null;
if (i < s.Length && s[i] != ',' && s[i] != '}') v = FlowAt(s, ref i);
outp[k] = v;
while (i < s.Length && (s[i] == ' ' || s[i] == ',')) i += 1;
}
}
if (i < s.Length && (s[i] == '"' || s[i] == '\''))
{
string v = QuotedAt(s, i, out int qi);
i = qi;
return v;
}
int j0 = i;
while (j0 < s.Length && s[j0] != ',' && s[j0] != ']' && s[j0] != '}') j0 += 1;
i = j0;
return PlainScalar(s.Substring(i, j0 - i).Trim());
}
/// `key: rest` split; null when the line is not a mapping entry.
private static string[] KeySplit(string s)
{
if (s.Length > 0 && (s[0] == '"' || s[0] == '\''))
{
string key;
int j;
try { key = QuotedAt(s, 0, out j); }
catch (InvalidOperationException) { return null; }
string rest = LTrim(s.Substring(j));
return rest.StartsWith(":") ? new[] { key, rest.Substring(1) } : null;
}
for (int j = 0; j < s.Length; j++)
{
if (s[j] == ':' && (j + 1 == s.Length || s[j + 1] == ' '))
{
return new[] { RTrim(s.Substring(0, j)), s.Substring(j + 1) };
}
}
return null;
}
private static List<Line> ContentLines(string text)
{
var outp = new List<Line>();
foreach (string raw in text.Split(new[] { '\n' }))
{
string crlf = raw.EndsWith("\r") ? raw.Substring(0, raw.Length - 1) : raw;
string indented = LTrim(crlf);
int indent = crlf.Length - indented.Length;
string body = RTrim(indented);
if (body.Length == 0 || body[0] == '#' || body[0] == '%' || body == "---") continue;
if (crlf.Substring(0, indent).IndexOf('\t') >= 0)
throw new InvalidOperationException("Invalid YAML: tab in indentation");
outp.Add(new Line(indent, body));
}
return outp;
}
private static bool IsItem(string s) { return s == "-" || s.StartsWith("- "); }
/// The node whose first line is ls[i] at the given indent; i advanced past it.
private static object BlockAt(List<Line> ls, ref int i, int indent)
{
if (IsItem(ls[i].Body))
{
var outp = new List<object>();
while (i < ls.Count && ls[i].Indent == indent && IsItem(ls[i].Body))
{
string content = ls[i].Body.Length > 2 ? ls[i].Body.Substring(2) : "";
object v;
if (content.Trim().Length == 0 || LTrim(content).StartsWith("#"))
{
i += 1;
if (i < ls.Count && ls[i].Indent > indent) v = BlockAt(ls, ref i, ls[i].Indent);
else v = null;
}
else
{
ls[i] = new Line(indent + 2, content);
v = BlockAt(ls, ref i, indent + 2);
}
outp.Add(v);
}
return outp;
}
if (KeySplit(ls[i].Body) == null) { object v = InlineValue(ls[i].Body); i += 1; return v; }
var map = new OrderedDictionary();
while (i < ls.Count && ls[i].Indent == indent && !IsItem(ls[i].Body) && KeySplit(ls[i].Body) != null)
{
string[] kv = KeySplit(ls[i].Body);
string key = kv[0];
string rest = kv[1].Trim();
i += 1;
if (rest.Length > 0) map[key] = InlineValue(rest);
else if (i < ls.Count && ls[i].Indent > indent) map[key] = BlockAt(ls, ref i, ls[i].Indent);
else if (i < ls.Count && ls[i].Indent == indent && IsItem(ls[i].Body)) map[key] = BlockAt(ls, ref i, indent);
else map[key] = null;
}
return map;
}
/// The value part of `key: value` — flow, quoted, or plain (comment cut).
private static object InlineValue(string rest)
{
char c0 = rest.Length > 0 ? rest[0] : '\0';
if (c0 == '[' || c0 == '{')
{
int j = 0;
object v = FlowAt(rest, ref j);
if (rest.Substring(j).Replace(" ", "").Replace("#", "").Length > 0)
throw new InvalidOperationException("Invalid YAML: trailing content after flow value");
return v;
}
if (c0 == '"' || c0 == '\'')
{
string v = QuotedAt(rest, 0, out int j);
if (rest.Substring(j).Replace(" ", "").Replace("#", "").Length > 0)
throw new InvalidOperationException("Invalid YAML: trailing content after quoted value");
return v;
}
int cut = rest.IndexOf(" #");
return PlainScalar(RTrim(cut >= 0 ? rest.Substring(0, cut) : rest).Trim());
}
/// The minimal parser: text → tree (OrderedDictionarys keep document order).
private static object ParseYaml(string text)
{
List<Line> ls = ContentLines(text);
if (ls.Count == 0) return null;
int i = 0;
object v = BlockAt(ls, ref i, ls[0].Indent);
if (i != ls.Count) throw new InvalidOperationException("Invalid YAML: inconsistent indentation");
return v;
}
/// JavaScript String(number) for the values the messages can hit.
private static string NumStr(object v)
{
if (v is long) return ((long)v).ToString(CultureInfo.InvariantCulture);
double d = (double)v;
if (!double.IsFinite(d)) return "null";
if (d == Math.Round(d) && Math.Abs(d) < 1e21) return ((long)d).ToString(CultureInfo.InvariantCulture);
return d.ToString(CultureInfo.InvariantCulture);
}
/// TS String(value) form for depends_on coercion and messages.
private static string TsStr(object v)
{
if (v == null) return "null";
if (v is bool) return (bool)v ? "true" : "false";
if (v is long || v is double) return NumStr(v);
if (v is string) return (string)v;
if (v is List<object>)
{
var b = new StringBuilder();
foreach (object e in (List<object>)v)
{
if (b.Length > 0) b.Append(',');
b.Append(TsStr(e));
}
return b.ToString();
}
return "[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.
public static string PortIssue(object entry)
{
if (entry is long n)
{
if (n < 0 || n > 65535) return "port " + n + " out of range 0-65535";
return null;
}
if (entry is double d)
{
if (!double.IsFinite(d) || d != Math.Round(d)) return "port must be a string or integer";
if (d < 0 || d > 65535) return "port " + NumStr(d) + " out of range 0-65535";
return null;
}
if (entry is string s)
{
int slash = s.IndexOf('/');
string proto = slash >= 0 ? s.Substring(slash + 1) : "";
if (proto.Length > 0 && proto != "tcp" && proto != "udp")
return "unknown protocol \"" + proto + "\" (use tcp or udp)";
string body = proto.Length == 0 ? s : s.Substring(0, slash);
string[] parts = body.Split(':');
// Host forms (localhost, IPv6 like ::1) carry non-numeric parts anywhere.
foreach (string p in parts) if (!DigitsRe.IsMatch(p)) return null;
if (parts.Length > 3) return "port must have 1-3 colon-separated parts";
foreach (string p in parts)
{
double n2 = double.Parse(p, CultureInfo.InvariantCulture);
if (n2 < 0 || n2 > 65535) return "port " + p + " out of range 0-65535";
}
return null;
}
return "port must be a string or integer"; // bool, null, maps, lists
}
private static bool ScalarOk(object v)
{
return v == null || v is string || v is bool || v is long || v is double;
}
/// Walk the document; append issues in TS order (root, services,
/// per-service in document order, then depends_on cycle detection).
public static List<ComposeIssue> Check(object root)
{
var outp = new List<ComposeIssue>();
Action<string, string> push = (path, message) => outp.Add(new ComposeIssue(path, message));
if (!(root is OrderedDictionary))
{
push("$", "compose root must be a mapping");
return outp;
}
var rootMap = (OrderedDictionary)root;
object servicesObj = rootMap.Contains("services") ? rootMap["services"] : null;
if (!(servicesObj is OrderedDictionary))
{
push("$.services", "missing or invalid \"services\" mapping");
return outp;
}
var services = (OrderedDictionary)servicesObj;
var ids = new List<string>();
foreach (object k in services.Keys) ids.Add((string)k);
if (ids.Count == 0) push("$.services", "services must not be empty");
foreach (string id in ids)
{
object svcObj = services[id];
string at = "$.services." + id;
if (!(svcObj is OrderedDictionary))
{
push(at, "service must be a mapping");
continue;
}
var svc = (OrderedDictionary)svcObj;
if (!svc.Contains("image") && !svc.Contains("build")) push(at, "service needs image or build");
if (svc.Contains("ports"))
{
object ports = svc["ports"];
if (!(ports is List<object>)) push(at + ".ports", "ports must be a list");
else
{
var items = (List<object>)ports;
for (int i = 0; i < items.Count; i++)
{
string msg = PortIssue(items[i]);
if (msg != null) push(at + ".ports[" + i + "]", msg);
}
}
}
if (svc.Contains("environment"))
{
object env = svc["environment"];
if (env is OrderedDictionary)
{
foreach (DictionaryEntryLike e in Entries((OrderedDictionary)env))
{
object v = e.Value;
if (!ScalarOk(v)) push(at + ".environment." + e.Key, "environment values must be scalars");
}
}
else if (env is List<object>)
{
var items = (List<object>)env;
for (int i = 0; i < items.Count; i++)
{
object e = items[i];
if (!(e is string) || !EnvKvRe.IsMatch((string)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 (svc.Contains("volumes") && !(svc["volumes"] is List<object>))
push(at + ".volumes", "volumes must be a list");
if (svc.Contains("depends_on"))
{
object dep = svc["depends_on"];
if (!(dep is List<object>) && !(dep is string) && !(dep is OrderedDictionary))
{
push(at + ".depends_on", "depends_on must be a string, list or mapping");
}
else
{
var names = new List<string>();
if (dep is OrderedDictionary) foreach (object k in ((OrderedDictionary)dep).Keys) names.Add((string)k);
else if (dep is List<object>) foreach (object e in (List<object>)dep) names.Add(TsStr(e));
else names.Add((string)dep);
for (int i = 0; i < names.Count; i++)
{
if (!services.Contains(names[i]))
push(at + ".depends_on[" + i + "]", "unknown service \"" + names[i] + "\"");
}
}
}
}
// depends_on cycle detection (map-form conditions do not affect the graph).
var color = new Dictionary<string, int>();
foreach (string id in ids) Visit(services, id, new List<string>(), color, push);
return outp;
}
private struct DictionaryEntryLike
{
public string Key;
public object Value;
}
private static List<DictionaryEntryLike> Entries(OrderedDictionary map)
{
var outp = new List<DictionaryEntryLike>();
foreach (object k in map.Keys) outp.Add(new DictionaryEntryLike { Key = (string)k, Value = map[k] });
return outp;
}
private static void Visit(OrderedDictionary services, string sid, List<string> stack,
Dictionary<string, int> color, Action<string, string> push)
{
int c;
if (color.TryGetValue(sid, out c))
{
if (c == 2) return;
if (c == 1)
{
int from = stack.IndexOf(sid);
var chain = stack.GetRange(from, stack.Count - from);
chain.Add(sid);
push("$.services", "depends_on cycle: " + string.Join(" -> ", chain));
return;
}
}
color[sid] = 1;
object svc = services.Contains(sid) ? services[sid] : null;
if (svc is OrderedDictionary && ((OrderedDictionary)svc).Contains("depends_on"))
{
object raw = ((OrderedDictionary)svc)["depends_on"];
var names = new List<string>();
if (raw is string) names.Add((string)raw);
else if (raw is List<object>)
{
foreach (object e in (List<object>)raw) if (e is string) names.Add((string)e);
}
else if (raw is OrderedDictionary) foreach (object k in ((OrderedDictionary)raw).Keys) names.Add((string)k);
foreach (string n in names)
{
if (services.Contains(n))
{
var next = new List<string>(stack);
next.Add(sid);
Visit(services, n, next, color, push);
}
}
}
color[sid] = 2;
}
/// Validate a Docker Compose file.
public static ComposeValidateResult ValidateCompose(string raw)
{
if (raw.Trim().Length == 0)
return new ComposeValidateResult(false, new List<ComposeIssue>(), "A compose document is required");
object root;
try
{
root = ParseYaml(raw);
}
catch (InvalidOperationException e)
{
return new ComposeValidateResult(false, new List<ComposeIssue>(), e.Message);
}
List<ComposeIssue> issues = Check(root);
return issues.Count == 0
? new ComposeValidateResult(true, new List<ComposeIssue>(), null)
: new ComposeValidateResult(false, issues, null);
}
}
// Example:
// var ok = ComposeValidator.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 == null
// var bad = ComposeValidator.ValidateCompose("services:\n web:\n image: nginx\n ports: [\"99999\"]");
// // bad.Issues: [{ Path "$.services.web.ports[0]", Message "port 99999 out of range 0-65535" }]
// ComposeValidator.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"
// ComposeValidator.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 →