GitHub Actions Validator — Ruby 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 Ruby implementation — the same logic the interactive tool runs, in a shareable, citable form.
# frozen_string_literal: true
# gh-actions-validator — GitHub Actions workflow structural validator.
#
# Language: Ruby (2.6+, standard library only — Ruby ships Psych, but it
# resolves YAML 1.1 scalars, so an unquoted `on:` key arrives as
# the boolean `true` and the rule checks would never find it (the
# classic GitHub Actions gotcha); this port therefore hand-rolls
# the same minimal YAML-subset parser as the sibling python.py)
# Source: CosmoDev polyglot showcase port of the `gh-actions-validator`
# tool, ported from src/lib/gh-actions-validator.ts (the canonical
# TypeScript implementation, which parses with the `yaml` npm
# package, YAML 1.2); Go twin:
# cli/gh-actions-validator/gh-actions-validator.go (yaml.v3).
# License: display source — part of CosmoDev's polyglot tool pages.
#
# Parses a workflow YAML document 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 TS/Go twins share. Not checked (by design, documented in
# the TS header): action versions, expressions (${{ }}) beyond syntax-free
# presence, runner label validity, duplicate YAML keys, `permissions`
# granularity.
#
# The hand-rolled subset covers 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 >
# (clip/strip; folded `>` joins lines with spaces) and comments — real
# workflow files stay inside it. No anchors/aliases, merge keys, multi-doc,
# or complex keys. 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. Ruby Hashes keep insertion order, so document order
# drives issue ordering (JS Object.keys parity) — the needs-cycle message
# names the DFS chain, starting with the first-declared job. Unterminated
# flow collections raise YamlError and surface as the fixed 'Invalid YAML'
# error. Never raises out of validate — errors travel in the result hash.
module GhActionsValidator
EVENTS = %w[
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
].freeze
# Raised by the parser on input outside the supported subset; validate
# converts it to the fixed 'Invalid YAML' error the twins report.
class YamlError < StandardError; end
module_function
def is_map(v)
v.is_a?(Hash)
end
def is_seq(v)
v.is_a?(Array)
end
def is_str(v)
v.is_a?(String)
end
# `#` starts a comment only at line start or after whitespace; quoted spans
# are skipped.
def strip_comment(line)
out = +""
quote = nil
line.chars.each_with_index do |c, i|
if quote
out << c
quote = nil if c == quote
next
end
if c == "'" || c == '"'
quote = c
out << c
next
end
break if c == "#" && (i.zero? || line[i - 1] == " " || line[i - 1] == "\t")
out << c
end
out.rstrip
end
# YAML 1.2 core resolution: only true/false are booleans, so unquoted `on`
# stays a string.
def resolve(s)
return true if %w[true True TRUE].include?(s)
return false if %w[false False FALSE].include?(s)
return nil if %w[null Null NULL ~].include?(s)
return Integer(s, 10) if s.match?(/\A[+-]?\d+\z/)
return Float(s) if s.match?(/\A[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\z/)
s
end
def unquote(s)
return s unless s.length >= 2 && s[0] == s[-1] && (s[0] == "'" || s[0] == '"')
body = s[1..-2]
return body.gsub("''", "'") if s[0] == "'"
esc = { "n" => "\n", "t" => "\t", "r" => "\r", '"' => '"', "\\" => "\\" }
out = +""
i = 0
while i < body.length
if body[i] == "\\" && i + 1 < body.length
out << (esc[body[i + 1]] || body[i + 1])
i += 2
else
out << body[i]
i += 1
end
end
out
end
# Split a flow collection body on top-level commas (quotes/brackets respected).
def split_flow(s)
parts = []
depth = 0
quote = nil
cur = +""
s.each_char do |c|
if quote
cur << c
quote = nil if c == quote
next
end
case c
when "'", '"'
quote = c
when "[", "{"
depth += 1
when "]", "}"
depth -= 1
when ","
if depth.zero?
parts << cur.strip
cur = +""
next
end
end
cur << c
end
last = cur.strip
parts << last unless last.empty?
parts
end
# Parse a flow collection / scalar. Raises YamlError on unterminated flow
# collections.
def parse_flow(s)
if s.start_with?("[")
raise YamlError, "unterminated flow sequence" unless s.end_with?("]")
return split_flow(s[1..-2]).map { |x| parse_flow(x) }
end
if s.start_with?("{")
raise YamlError, "unterminated flow mapping" unless s.end_with?("}")
m = {}
split_flow(s[1..-2]).each do |item|
key, rest = split_key(item)
m[key] = parse_flow(rest)
end
return m
end
return unquote(s) if s.length >= 2 && (s[0] == "'" || s[0] == '"') && s[-1] == s[0]
resolve(s)
end
# Split 'key: rest' at the first top-level colon (followed by space or end).
def split_key(text)
quote = nil
depth = 0
text.chars.each_with_index do |c, i|
if quote
quote = nil if c == quote
next
end
case c
when "'", '"'
quote = c
when "[", "{"
depth += 1
when "]", "}"
depth -= 1
when ":"
if depth.zero? && (i + 1 == text.length || text[i + 1] == " " || text[i + 1] == "\t")
return [unquote(text[0...i].strip), text[(i + 1)..].strip]
end
end
end
# fallback: quoted key immediately followed by a colon, e.g. 'key':value
if text[0] == "'" || text[0] == '"'
end_i = text.index(text[0], 1)
return [unquote(text[0..end_i]), text[(end_i + 2)..].strip] if end_i && end_i + 1 < text.length && text[end_i + 1] == ":"
end
[unquote(text.strip), ""]
end
# Prepare (indent, text) pairs: tabs normalized, `---`/`...` markers,
# comments, blanks out.
def prepare_lines(raw)
lines = []
raw.split("\n").each do |line|
bare = line.strip
next if bare == "---" || bare == "..."
text = strip_comment(line.gsub("\t", " "))
next if text.strip.empty?
indent = text.length - text[/\A */].length
lines << [indent, text.strip]
end
lines
end
def seq_marker(text)
text == "-" || text.start_with?("- ")
end
# Consume a | or > block scalar body; returns [value, next_i].
def block_scalar(lines, i, indent, rest)
fold = rest[0] == ">"
chomp_strip = rest.end_with?("-")
body = []
j = i
while j < lines.length
ind, text = lines[j]
break if ind <= indent
body << text
j += 1
end
joined = body.join(fold ? " " : "\n")
joined += "\n" if !chomp_strip && !body.empty?
[joined, j]
end
# Resolve a rest-of-line value, consuming block scalar bodies.
def inline_value(lines, i, indent, rest)
return block_scalar(lines, i + 1, indent, rest) if rest[0] == "|" || rest[0] == ">"
[parse_flow(rest), i + 1]
end
def parse_map(lines, i, indent)
m = {}
while i < lines.length && lines[i][0] == indent && !seq_marker(lines[i][1])
key, rest = split_key(lines[i][1])
if rest != ""
m[key], i = inline_value(lines, i, indent, rest)
else
j = i + 1
if j < lines.length && lines[j][0] > indent
m[key], i = parse_block(lines, j, lines[j][0])
elsif j < lines.length && lines[j][0] == indent && seq_marker(lines[j][1])
m[key], i = parse_seq(lines, j, indent)
else
m[key] = nil
i = j
end
end
end
[m, i]
end
def parse_seq(lines, i, indent)
seq = []
while i < lines.length && lines[i][0] == indent && seq_marker(lines[i][1])
text = lines[i][1]
rest = text[1..].sub(/\A +/, "")
rest_col = indent + (text.length - rest.length)
if rest.empty?
j = i + 1
if j < lines.length && lines[j][0] > indent
val, i = parse_block(lines, j, lines[j][0])
seq << val
else
seq << nil
i = j
end
elsif (rest.include?(":") && split_key(rest)[1] != "") || rest.end_with?(":")
# inline map start ("- key: value", more pairs may follow at rest_col)
m = {}
key, r2 = split_key(rest)
if r2 != ""
m[key] = inline_value(lines, i, rest_col, r2)[0]
else
j = i + 1
if j < lines.length && lines[j][0] > rest_col
m[key] = parse_block(lines, j, lines[j][0])[0]
else
m[key] = nil
end
end
i += 1
while i < lines.length && lines[i][0] == rest_col && !seq_marker(lines[i][1])
k2, r3 = split_key(lines[i][1])
if r3 != ""
m[k2] = inline_value(lines, i, rest_col, r3)[0]
i += 1
else
j = i + 1
if j < lines.length && lines[j][0] > rest_col
m[k2], i = parse_block(lines, j, lines[j][0])
else
m[k2] = nil
i = j
end
end
end
seq << m
else
seq_item, i = inline_value(lines, i, rest_col, rest)
seq << seq_item
end
end
[seq, i]
end
def parse_block(lines, i, indent)
return [nil, i] if i >= lines.length || lines[i][0] < indent
return parse_seq(lines, i, indent) if seq_marker(lines[i][1])
parse_map(lines, i, indent)
end
def parse_yaml(raw)
lines = prepare_lines(raw)
return nil if lines.empty?
parse_block(lines, 0, lines[0][0])[0]
end
def issue(path, message)
{ path: path, message: message }
end
# Validate a parsed workflow document; the TS check() in Ruby form.
def check(root)
out = []
unless is_map(root)
out << issue("$", "workflow root must be a mapping")
return out
end
out << issue("$", 'missing required key "jobs"') unless root.key?("jobs")
out << issue("$", 'missing required key "on"') unless root.key?("on")
# on: string | array of strings | map of event -> config
if root.key?("on")
on = root["on"]
if is_str(on)
out << issue("$.on", "unknown event \"#{on}\"") unless EVENTS.include?(on)
elsif is_seq(on)
on.each_with_index do |e, i|
if !is_str(e)
out << issue("$.on[#{i}]", "event list entries must be strings")
elsif !EVENTS.include?(e)
out << issue("$.on[#{i}]", "unknown event \"#{e}\"")
end
end
elsif is_map(on)
on.each_key do |name|
out << issue("$.on.#{name}", "unknown event \"#{name}\"") unless EVENTS.include?(name)
cfg = on[name]
if is_map(cfg) && cfg.key?("branches") && !is_seq(cfg["branches"]) && !is_str(cfg["branches"])
out << issue("$.on.#{name}.branches", "branches must be a string or a list")
end
end
else
out << issue("$.on", "on must be a string, list or mapping")
end
end
jobs = root["jobs"]
unless is_map(jobs)
out << issue("$.jobs", "jobs must be a mapping") if root.key?("jobs")
return out
end
job_ids = jobs.keys
out << issue("$.jobs", "jobs must not be empty") if job_ids.empty?
job_ids.each do |id|
job = jobs[id]
at = "$.jobs.#{id}"
unless is_map(job)
out << issue(at, "job must be a mapping")
next
end
reusable = is_str(job["uses"])
ro = job["runs-on"]
out << issue("#{at}.runs-on", "job needs runs-on (or a reusable-workflow uses)") if !reusable && !is_str(ro) && !is_seq(ro)
out << issue("#{at}.steps", "job needs steps") if !reusable && !job.key?("steps")
steps = job["steps"]
if is_seq(steps)
out << issue("#{at}.steps", "steps must not be empty") if steps.empty?
steps.each_with_index do |step, i|
sat = "#{at}.steps[#{i}]"
unless is_map(step)
out << issue(sat, "step must be a mapping")
next
end
has_run = is_str(step["run"])
has_uses = is_str(step["uses"])
out << issue(sat, "step needs run or uses") if !has_run && !has_uses
out << issue(sat, "step has both run and uses - pick one") if has_run && has_uses
end
elsif job.key?("steps")
out << issue("#{at}.steps", "steps must be a list")
end
next unless job.key?("needs")
n = job["needs"]
needs = is_seq(n) ? n : ([n] if is_str(n))
if needs.nil?
out << issue("#{at}.needs", "needs must be a string or a list")
else
needs.each_with_index do |x, i|
if !is_str(x)
out << issue("#{at}.needs[#{i}]", "needs entries must be strings")
elsif jobs.key?(x)
next
else
out << issue("#{at}.needs[#{i}]", "unknown job \"#{x}\"")
end
end
end
end
# needs-graph cycle detection: DFS from every job over declared, known
# edges. color: 1 = visiting, 2 = done.
color = Hash.new(0)
visit = lambda do |jid, stack|
return if color[jid] == 2
if color[jid] == 1
start = stack.index(jid)
chain = stack[start..] + [jid]
out << issue("$.jobs", "needs cycle: #{chain.join(' -> ')}")
return
end
color[jid] = 1
job = jobs[jid]
if is_map(job)
n = job["needs"]
if is_str(n) || is_seq(n)
(is_seq(n) ? n : [n]).each do |x|
visit.call(x, stack + [jid]) if is_str(x) && jobs.key?(x)
end
end
end
color[jid] = 2
end
job_ids.each { |jid| visit.call(jid, []) }
out
end
# Validate a GitHub Actions workflow YAML document. Returns
# {valid:, issues: [{path, message}], error:} — error is nil when the
# verdict is real (TS: error: null).
def validate(raw)
return { valid: false, issues: [], error: "A workflow document is required" } if raw.strip.empty?
begin
root = parse_yaml(raw)
rescue YamlError, StandardError
return { valid: false, issues: [], error: "Invalid YAML" }
end
issues = check(root)
{ valid: issues.empty?, issues: issues, error: nil }
end
# Example:
# GhActionsValidator.validate(<<~YAML)["issues"]
# on: push
# jobs:
# a:
# needs: b
# runs-on: ubuntu-latest
# steps:
# - run: make
# b:
# needs: a
# runs-on: ubuntu-latest
# steps:
# - run: make
# YAML
# => [{path: "$.jobs", message: "needs cycle: a -> b -> a"}]
end
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 →