GitHub Actions Validator — Python source
Check a workflow YAML before you push: on-shape, jobs, runs-on, steps with run or uses, and the needs graph including cycle detection — every issue reported at its path. Runs locally in your browser.
This is the Python implementation — the same logic the interactive tool runs, in a shareable, citable form.
"""gh-actions-validator — GitHub Actions workflow structural validator. Python
port (canonical TS: src/lib/gh-actions-validator.ts; Go twin:
cli/gh-actions-validator). Parses a workflow YAML and checks structural
rules: root shape, `on:` event shape, jobs with a needs-graph (unknown needs,
acyclicity), runs-on (unless the job delegates to a reusable workflow via
uses:), and steps that are exactly one of run/uses. The rule set and message
texts are the contract. The standard library ships no YAML parser, so this
file carries a terse YAML-subset parser: block mappings/sequences (including
child sequences at the parent key's indent and `- key: value` inline map
items), flow sequences/maps, quoted and plain scalars, block scalars | and >
(clipped/strip; folded '>' joins lines with spaces), and comments. No
anchors/aliases, merge keys, multi-doc, or complex keys — real workflow
files stay inside the subset. Scalar resolution is YAML 1.2 as the `yaml`
npm package and yaml.v3 resolve it: only true/false are booleans, so the
unquoted `on` key stays a string. Dict insertion order drives issue
ordering (JS Object.keys parity). Parse errors travel as 'Invalid YAML'
(the TS surfaces the yaml package's own message). Never raises — errors
travel in the result dict.
"""
EVENTS = {
"push", "pull_request", "pull_request_target", "workflow_dispatch", "schedule", "release",
"issues", "issue_comment", "watch", "fork", "create", "delete", "deployment", "page_build",
"public", "pull_request_review", "pull_request_review_comment", "push_tag", "registry_package",
"repository_dispatch", "status", "workflow_run", "check_run", "check_suite", "label",
}
def _is_map(v):
return isinstance(v, dict)
def _is_seq(v):
return isinstance(v, list)
def _is_str(v):
return isinstance(v, str)
def _strip_comment(line):
out = []
quote = None
for i, c in enumerate(line):
if quote:
out.append(c)
if c == quote:
quote = None
continue
if c in "'\"":
quote = c
out.append(c)
continue
if c == "#" and (i == 0 or line[i - 1] in " \t"):
break
out.append(c)
return "".join(out).rstrip()
def _resolve(s):
if s in ("true", "True", "TRUE"):
return True
if s in ("false", "False", "FALSE"):
return False
if s in ("null", "Null", "NULL", "~"):
return None
try:
return int(s)
except ValueError:
pass
try:
return float(s)
except ValueError:
pass
return s
def _unquote(s):
if len(s) >= 2 and s[0] == s[-1] and s[0] in "'\"":
body = s[1:-1]
if s[0] == "'":
return body.replace("''", "'")
out = []
i = 0
while i < len(body):
if body[i] == "\\" and i + 1 < len(body):
esc = {"n": "\n", "t": "\t", "r": "\r", '"': '"', "\\": "\\"}
out.append(esc.get(body[i + 1], body[i + 1]))
i += 2
else:
out.append(body[i])
i += 1
return "".join(out)
return s
def _split_flow(s):
"""Split a flow collection body on top-level commas."""
parts = []
depth = 0
quote = None
cur = []
for c in s:
if quote:
cur.append(c)
if c == quote:
quote = None
continue
if c in "'\"":
quote = c
elif c in "[{":
depth += 1
elif c in "]}":
depth -= 1
elif c == "," and depth == 0:
parts.append("".join(cur).strip())
cur = []
continue
cur.append(c)
last = "".join(cur).strip()
if last:
parts.append(last)
return parts
def _parse_flow(s):
if s.startswith("[") and s.endswith("]"):
return [_scalar_or_flow(x) for x in _split_flow(s[1:-1])]
if s.startswith("{") and s.endswith("}"):
m = {}
for item in _split_flow(s[1:-1]):
key, _, rest = _split_key(item)
m[key] = _scalar_or_flow(rest)
return m
if s and s[0] in "'\"" and s[-1] == s[0]:
return _unquote(s)
return _resolve(s)
def _split_key(text):
"""Split 'key: rest' at the first top-level colon."""
quote = None
depth = 0
for i, c in enumerate(text):
if quote:
if c == quote:
quote = None
continue
if c in "'\"":
quote = c
elif c in "[{":
depth += 1
elif c in "]}":
depth -= 1
elif c == ":" and depth == 0 and (i + 1 == len(text) or text[i + 1] in " \t"):
return _unquote(text[:i].strip()), text[i + 1:].strip()
if text.startswith("'") or text.startswith('"'):
q = text[0]
end = text.find(q, 1)
if end != -1 and end + 1 < len(text) and text[end + 1] == ":":
return _unquote(text[:end + 1]), text[end + 2:].strip()
return _unquote(text.strip()), ""
class _Lines:
def __init__(self, raw):
self.items = []
for line in raw.split("\n"):
if line.strip() in ("---", "..."):
continue
text = _strip_comment(line.expandtabs(2))
if not text.strip():
continue
indent = len(text) - len(text.lstrip(" "))
self.items.append((indent, text.strip()))
def __len__(self):
return len(self.items)
def __getitem__(self, i):
return self.items[i]
def _seq_marker(text):
return text == "-" or text.startswith("- ")
def _block_scalar(lines, i, indent, rest):
"""Consume a | or > block scalar body; returns (value, next_i)."""
fold = rest[0] == ">"
chomp_strip = rest.endswith("-")
body = []
base = None
j = i
while j < len(lines):
ind, text = lines[j]
if ind <= indent:
break
if base is None:
base = ind
body.append(text if ind >= base else text)
j += 1
joined = ("\n" if not fold else " ").join(body)
if not chomp_strip and body:
joined += "\n"
return joined, j
def _inline_value(lines, i, indent, rest):
"""Resolve a rest-of-line value, consuming block scalar bodies."""
if rest and rest[0] in "|>":
return _block_scalar(lines, i + 1, indent, rest)
return _parse_flow(rest), i + 1
def _parse_map(lines, i, indent):
m = {}
while i < len(lines) and lines[i][0] == indent and not _seq_marker(lines[i][1]):
key, rest = _split_key(lines[i][1])
if rest:
val, i = _inline_value(lines, i, indent, rest)
else:
j = i + 1
if j < len(lines) and lines[j][0] > indent:
val, i = _parse_block(lines, j, lines[j][0])
elif j < len(lines) and lines[j][0] == indent and _seq_marker(lines[j][1]):
val, i = _parse_seq(lines, j, indent)
else:
val, i = None, j
m[key] = val
return m, i
def _parse_seq(lines, i, indent):
seq = []
while i < len(lines) and lines[i][0] == indent and _seq_marker(lines[i][1]):
text = lines[i][1]
rest = text[1:].lstrip()
rest_col = indent + (len(text) - len(rest))
if not rest:
j = i + 1
if j < len(lines) and lines[j][0] > indent:
val, i = _parse_block(lines, j, lines[j][0])
else:
val, i = None, j
elif ":" in rest and _split_key(rest)[1] != "" or rest.endswith(":"):
# inline map start ("- key: value", more pairs may follow at rest_col)
m = {}
key, r2 = _split_key(rest)
if r2:
val, _ = _inline_value(lines, i, rest_col, r2)
else:
j = i + 1
if j < len(lines) and lines[j][0] > rest_col:
val, _ = _parse_block(lines, j, lines[j][0])
else:
val = None
m[key] = val
i += 1
while i < len(lines) and lines[i][0] == rest_col and not _seq_marker(lines[i][1]):
k2, r3 = _split_key(lines[i][1])
if r3:
v2, _ = _inline_value(lines, i, rest_col, r3)
else:
j = i + 1
if j < len(lines) and lines[j][0] > rest_col:
v2, i = _parse_block(lines, j, lines[j][0])
else:
v2, i = None, j
m[k2] = v2
val = m
else:
val, i = _inline_value(lines, i, rest_col, rest)
seq.append(val)
return seq, i
def _parse_block(lines, i, indent):
if i >= len(lines) or lines[i][0] < indent:
return None, i
if _seq_marker(lines[i][1]):
return _parse_seq(lines, i, indent)
return _parse_map(lines, i, indent)
def _parse_yaml(raw):
lines = _Lines(raw)
if len(lines) == 0:
return None
root, _ = _parse_block(lines, 0, lines[0][0])
return root
def _issue(out, path, message):
out.append({"path": path, "message": message})
def _check(root, out):
if not _is_map(root):
_issue(out, "$", "workflow root must be a mapping")
return
if "jobs" not in root:
_issue(out, "$", 'missing required key "jobs"')
if "on" not in root:
_issue(out, "$", 'missing required key "on"')
if "on" in root:
on = root["on"]
if _is_str(on):
if on not in EVENTS:
_issue(out, "$.on", 'unknown event "%s"' % on)
elif _is_seq(on):
for i, e in enumerate(on):
if not _is_str(e):
_issue(out, "$.on[%d]" % i, "event list entries must be strings")
elif e not in EVENTS:
_issue(out, "$.on[%d]" % i, 'unknown event "%s"' % e)
elif _is_map(on):
for name in on:
if name not in EVENTS:
_issue(out, "$.on.%s" % name, 'unknown event "%s"' % name)
cfg = on[name]
if _is_map(cfg) and "branches" in cfg and not _is_seq(cfg["branches"]) and not _is_str(cfg["branches"]):
_issue(out, "$.on.%s.branches" % name, "branches must be a string or a list")
else:
_issue(out, "$.on", "on must be a string, list or mapping")
jobs = root.get("jobs")
if not _is_map(jobs):
if "jobs" in root:
_issue(out, "$.jobs", "jobs must be a mapping")
return
job_ids = list(jobs)
if not job_ids:
_issue(out, "$.jobs", "jobs must not be empty")
for jid in job_ids:
job = jobs[jid]
at = "$.jobs.%s" % jid
if not _is_map(job):
_issue(out, at, "job must be a mapping")
continue
reusable = _is_str(job.get("uses"))
ro = job.get("runs-on")
if not reusable and not _is_str(ro) and not _is_seq(ro):
_issue(out, at + ".runs-on", "job needs runs-on (or a reusable-workflow uses)")
if not reusable and "steps" not in job:
_issue(out, at + ".steps", "job needs steps")
steps = job.get("steps")
if _is_seq(steps):
if not steps:
_issue(out, at + ".steps", "steps must not be empty")
for i, step in enumerate(steps):
sat = "%s.steps[%d]" % (at, i)
if not _is_map(step):
_issue(out, sat, "step must be a mapping")
continue
has_run = _is_str(step.get("run"))
has_uses = _is_str(step.get("uses"))
if not has_run and not has_uses:
_issue(out, sat, "step needs run or uses")
if has_run and has_uses:
_issue(out, sat, "step has both run and uses - pick one")
elif "steps" in job:
_issue(out, at + ".steps", "steps must be a list")
if "needs" in job:
n = job["needs"]
if _is_seq(n):
needs = n
elif _is_str(n):
needs = [n]
else:
needs = None
if needs is None:
_issue(out, at + ".needs", "needs must be a string or a list")
else:
for i, x in enumerate(needs):
if not _is_str(x):
_issue(out, "%s.needs[%d]" % (at, i), "needs entries must be strings")
elif x not in jobs:
_issue(out, "%s.needs[%d]" % (at, i), 'unknown job "%s"' % x)
# needs-graph cycle detection: DFS from every job over declared, known edges.
color = {}
def visit(jid, stack):
if color.get(jid) == 2:
return
if color.get(jid) == 1:
start = stack.index(jid)
chain = stack[start:] + [jid]
_issue(out, "$.jobs", "needs cycle: %s" % " -> ".join(chain))
return
color[jid] = 1
job = jobs.get(jid)
n = job.get("needs") if _is_map(job) else None
if _is_map(job) and (_is_str(n) or _is_seq(n)):
for x in (n if _is_seq(n) else [n]):
if _is_str(x) and x in jobs:
visit(x, stack + [jid])
color[jid] = 2
for jid in job_ids:
visit(jid, [])
def validate_gh_actions(raw):
"""Validate a GitHub Actions workflow YAML document. Returns
{valid, issues: [{path, message}], error} — error is None when the
verdict is real (TS: error: null)."""
if not raw.strip():
return {"valid": False, "issues": [], "error": "A workflow document is required"}
try:
root = _parse_yaml(raw)
except Exception:
return {"valid": False, "issues": [], "error": "Invalid YAML"}
issues = []
_check(root, issues)
return {"valid": not issues, "issues": issues, "error": None}
# Example:
# validate_gh_actions("on: push\njobs:\n a:\n needs: b\n runs-on: ubuntu-latest\n steps:\n - run: make\n b:\n needs: a\n runs-on: ubuntu-latest\n steps:\n - run: make")["issues"]
# → [{"path": "$.jobs", "message": "needs cycle: a -> b -> a"}]
if __name__ == "__main__":
r = validate_gh_actions(
"name: CI\non:\n push:\n branches: [main]\njobs:\n build:\n needs: test\n"
" runs-on: ubuntu-latest\n steps:\n - run: make\n"
" test:\n needs: build\n runs-on: ubuntu-latest\n steps:\n - run: make\n")
print(r)
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 →