Skip to content

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

// Package ghactionsvalidator is the Go twin of CosmoDev's
// src/lib/gh-actions-validator.ts (dual source: the web lib is TypeScript, the
// CLI lib is Go — kept in lock-step). Pure + deterministic, never panics. The
// table-driven tests in gh-actions-validator_test.go share vectors with
// src/lib/gh-actions-validator.test.ts so the two implementations are held to
// the same contract.
//
// Pure surface of the GitHub Actions Validator: parse a workflow YAML document
// and check 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.
//
// Not checked (by design, mirroring the TS header): action versions,
// expressions (${{ }}) beyond syntax-free presence, runner label validity,
// duplicate YAML keys, `permissions` granularity.
//
// Parsing uses yaml.v3 where the TS lib uses the `yaml` npm package with
// { merge: true }. Scalar resolution matches the TS parser: yaml.v3 resolves
// only true/false as booleans, so an unquoted `on` key stays a string and
// `on: 42` is reported as malformed, exactly like in the TS.
//
// The Go twin walks the parsed yaml.Node tree instead of decoding into
// map[string]interface{} so mapping keys keep document order (JS Object.keys
// exposes insertion order; Go map iteration is randomized). Job iteration
// order is observable: the needs-cycle message names the DFS chain, and the
// TS test pins it to start with the first-declared job.
package ghactionsvalidator

import (
	"fmt"
	"strings"

	"gopkg.in/yaml.v3"
)

// WorkflowIssue mirrors the WorkflowIssue interface in the TS lib: where the
// problem sits (a JSONPath-like locator, e.g. "$.jobs.build.steps[0]") and
// what is wrong (a fixed message string from the rule set).
type WorkflowIssue struct {
	Path    string
	Message string
}

// GhActionsValidateResult mirrors the TS GhActionsValidateResult union. Exactly
// one of the three TS shapes occurs:
//
//   - {valid: true,  issues: [],    error: null}  → Valid=true, Issues empty, Error nil
//   - {valid: false, issues: [...], error: null}  → Valid=false, Issues set, Error nil
//   - {valid: false, issues: [],    error: "msg"} → Valid=false, Issues empty, Error set
//
// Error is nil (TS null) unless the document itself failed to parse.
type GhActionsValidateResult struct {
	Valid  bool
	Issues []WorkflowIssue
	Error  *string // nil when the document parsed cleanly (TS: error: null)
}

// strptr returns a pointer to s, building the nullable Error field.
func strptr(s string) *string { return &s }

// events is the known trigger-event set, mirroring EVENTS in the TS lib.
var events = map[string]bool{
	"push": true, "pull_request": true, "pull_request_target": true,
	"workflow_dispatch": true, "schedule": true, "release": true,
	"issues": true, "issue_comment": true, "watch": true, "fork": true,
	"create": true, "delete": true, "deployment": true, "page_build": true,
	"public": true, "pull_request_review": true, "pull_request_review_comment": true,
	"push_tag": true, "registry_package": true, "repository_dispatch": true,
	"status": true, "workflow_run": true, "check_run": true, "check_suite": true,
	"label": true,
}

// yamlMap is a YAML mapping that remembers document key order, mirroring the
// insertion order JS Object.keys exposes after yaml.parse. It represents the
// map arm of the TS Node type (null | bool | number | string | array | map);
// null/bool/number/string map to nil/bool/int|float64/string and arrays to
// []any directly.
type yamlMap struct {
	keys []string
	vals map[string]any
}

// get returns the value for key and whether the key exists (TS `'k' in obj`).
func (m *yamlMap) get(key string) (any, bool) {
	if m == nil {
		return nil, false
	}
	v, ok := m.vals[key]
	return v, ok
}

// has reports whether key exists (TS `'k' in obj`).
func (m *yamlMap) has(key string) bool {
	_, ok := m.get(key)
	return ok
}

// isMap / isList / isString mirror the TS typeof/Array.isArray guards.
func isMap(v any) bool    { _, ok := v.(*yamlMap); return ok }
func isList(v any) bool   { _, ok := v.([]any); return ok }
func isString(v any) bool { _, ok := v.(string); return ok }

// nodeToValue converts a parsed yaml.Node into the generic value space above,
// preserving mapping key order.
func nodeToValue(n *yaml.Node) any {
	switch n.Kind {
	case yaml.DocumentNode:
		if len(n.Content) == 0 {
			return nil
		}
		return nodeToValue(n.Content[0])
	case yaml.MappingNode:
		m := &yamlMap{vals: make(map[string]any, len(n.Content)/2)}
		for i := 0; i+1 < len(n.Content); i += 2 {
			k := n.Content[i].Value
			m.keys = append(m.keys, k)
			m.vals[k] = nodeToValue(n.Content[i+1])
		}
		return m
	case yaml.SequenceNode:
		list := make([]any, 0, len(n.Content))
		for _, c := range n.Content {
			list = append(list, nodeToValue(c))
		}
		return list
	case yaml.ScalarNode:
		var v any
		if err := n.Decode(&v); err != nil {
			return n.Value // fall back to the raw scalar text, never panic
		}
		return v
	default:
		if n.Alias != nil { // alias nodes resolve to their anchor's value
			return nodeToValue(n.Alias)
		}
		return nil
	}
}

// parseYAML parses raw into the generic value space (nil | bool | int |
// float64 | string | []any | *yamlMap). It is a package variable so tests can
// simulate parser failures the way the TS suite mocks yaml.parse — including
// the non-Error throw that exercises the 'Invalid YAML' fallback.
var parseYAML = func(raw string) (any, error) {
	var doc yaml.Node
	if err := yaml.Unmarshal([]byte(raw), &doc); err != nil {
		return nil, err
	}
	if doc.Kind == 0 {
		return nil, nil // empty document (comments only) parses to null
	}
	return nodeToValue(&doc), nil
}

// check validates a parsed workflow document and returns the issues in the
// same order the TS check() appends them. It is the Go twin of check() in
// src/lib/gh-actions-validator.ts.
func check(root any) []WorkflowIssue {
	issues := []WorkflowIssue{}
	push := func(path, message string) {
		issues = append(issues, WorkflowIssue{Path: path, Message: message})
	}

	if !isMap(root) {
		push("$", "workflow root must be a mapping")
		return issues
	}
	rootMap := root.(*yamlMap)

	if !rootMap.has("jobs") {
		push("$", `missing required key "jobs"`)
	}
	if !rootMap.has("on") {
		push("$", `missing required key "on"`)
	}

	// on: string | array of strings | map of event -> config
	if on, ok := rootMap.get("on"); ok {
		switch {
		case isString(on):
			if !events[on.(string)] {
				push("$.on", "unknown event \""+on.(string)+"\"")
			}
		case isList(on):
			for i, e := range on.([]any) {
				if !isString(e) {
					push(fmt.Sprintf("$.on[%d]", i), "event list entries must be strings")
				} else if !events[e.(string)] {
					push(fmt.Sprintf("$.on[%d]", i), "unknown event \""+e.(string)+"\"")
				}
			}
		case isMap(on):
			m := on.(*yamlMap)
			for _, name := range m.keys {
				cfg, _ := m.get(name)
				if !events[name] {
					push("$.on."+name, "unknown event \""+name+"\"")
				}
				if cm, ok := cfg.(*yamlMap); ok {
					if branches, ok := cm.get("branches"); ok && !isList(branches) && !isString(branches) {
						push("$.on."+name+".branches", "branches must be a string or a list")
					}
				}
			}
		default:
			push("$.on", "on must be a string, list or mapping")
		}
	}

	jobsV, hasJobs := rootMap.get("jobs")
	if !isMap(jobsV) {
		if hasJobs {
			push("$.jobs", "jobs must be a mapping")
		}
		return issues
	}
	jobs := jobsV.(*yamlMap)
	if len(jobs.keys) == 0 {
		push("$.jobs", "jobs must not be empty")
	}

	for _, id := range jobs.keys {
		jobV, _ := jobs.get(id)
		at := "$.jobs." + id
		job, ok := jobV.(*yamlMap)
		if !ok {
			push(at, "job must be a mapping")
			continue
		}
		usesV, _ := job.get("uses")
		reusable := isString(usesV)
		runsOn, _ := job.get("runs-on")
		if !reusable && !isString(runsOn) && !isList(runsOn) {
			push(at+".runs-on", "job needs runs-on (or a reusable-workflow uses)")
		}
		stepsV, hasSteps := job.get("steps")
		if !reusable && !hasSteps {
			push(at+".steps", "job needs steps")
		}
		if steps, ok := stepsV.([]any); ok {
			if len(steps) == 0 {
				push(at+".steps", "steps must not be empty")
			}
			for i, stepV := range steps {
				sat := fmt.Sprintf("%s.steps[%d]", at, i)
				step, ok := stepV.(*yamlMap)
				if !ok {
					push(sat, "step must be a mapping")
					continue
				}
				runV, _ := step.get("run")
				usesV2, _ := step.get("uses")
				hasRun := isString(runV)
				hasUses := isString(usesV2)
				if !hasRun && !hasUses {
					push(sat, "step needs run or uses")
				}
				if hasRun && hasUses {
					push(sat, "step has both run and uses - pick one")
				}
			}
		} else if hasSteps {
			push(at+".steps", "steps must be a list")
		}
		if needsV, ok := job.get("needs"); ok {
			if isList(needsV) {
				for i, n := range needsV.([]any) {
					if !isString(n) {
						push(fmt.Sprintf("%s.needs[%d]", at, i), "needs entries must be strings")
					} else if !jobs.has(n.(string)) {
						push(fmt.Sprintf("%s.needs[%d]", at, i), "unknown job \""+n.(string)+"\"")
					}
				}
			} else if isString(needsV) {
				if !jobs.has(needsV.(string)) {
					push(at+".needs[0]", "unknown job \""+needsV.(string)+"\"")
				}
			} else {
				push(at+".needs", "needs must be a string or a list")
			}
		}
	}

	// needs-graph cycle detection: DFS from every job over declared, known
	// edges. color: 1 = visiting, 2 = done (mirrors the TS Map<number>).
	color := map[string]int{}
	var visit func(id string, stack []string)
	visit = func(id string, stack []string) {
		if color[id] == 2 {
			return
		}
		if color[id] == 1 {
			from := 0
			for i, s := range stack {
				if s == id {
					from = i
					break
				}
			}
			chain := make([]string, 0, len(stack)-from+1)
			chain = append(chain, stack[from:]...)
			chain = append(chain, id)
			push("$.jobs", "needs cycle: "+strings.Join(chain, " -> "))
			return
		}
		color[id] = 1
		if jobV, ok := jobs.get(id); ok {
			if job, ok := jobV.(*yamlMap); ok {
				if needsV, ok := job.get("needs"); ok && (isString(needsV) || isList(needsV)) {
					var list []any
					if s, ok := needsV.(string); ok {
						list = []any{s}
					} else {
						list = needsV.([]any)
					}
					for _, n := range list {
						if s, ok := n.(string); ok && jobs.has(s) {
							next := make([]string, len(stack)+1)
							copy(next, stack)
							next[len(stack)] = id
							visit(s, next)
						}
					}
				}
			}
		}
		color[id] = 2
	}
	for _, id := range jobs.keys {
		visit(id, []string{})
	}

	return issues
}

// ValidateGhActions validates a GitHub Actions workflow YAML document. It is
// the Go twin of validateGhActions() in src/lib/gh-actions-validator.ts and
// must agree with it on every shared vector.
func ValidateGhActions(raw string) GhActionsValidateResult {
	if strings.TrimSpace(raw) == "" {
		return GhActionsValidateResult{Valid: false, Issues: []WorkflowIssue{}, Error: strptr("A workflow document is required")}
	}
	root, err := parseYAML(raw)
	if err != nil {
		msg := err.Error()
		if msg == "" {
			msg = "Invalid YAML" // TS: a thrown non-Error has no message to surface
		}
		return GhActionsValidateResult{Valid: false, Issues: []WorkflowIssue{}, Error: strptr(msg)}
	}
	issues := check(root)
	if len(issues) == 0 {
		return GhActionsValidateResult{Valid: true, Issues: []WorkflowIssue{}, Error: nil}
	}
	return GhActionsValidateResult{Valid: false, Issues: issues, Error: nil}
}

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 →