package runs import ( json "encoding/json/v2" "fmt" "regexp" "strings" "gopkg.in/yaml.v3" ) // StepResult is the output later steps can reference as // steps..summary and steps..result.. Target is not referenceable; // the run's trail shows it beside the summary. type StepResult struct { Summary string `json:"summary"` Result map[string]any `json:"result,omitzero"` Target *Target `json:"target,omitzero"` } // Target is the item a step acted on: its kind, such as a messaging channel, // and its identifier. type Target struct { Kind string `json:"kind"` ID string `json:"id"` } // referencePattern matches {{ path }} in a step's string settings. var referencePattern = regexp.MustCompile(`\{\{\s*([^{}\s]+)\s*\}\}`) // soleReferencePattern matches a standalone reference, which preserves the // referenced value's type. var soleReferencePattern = regexp.MustCompile(`^\s*\{\{\s*([^{}\s]+)\s*\}\}\s*$`) // taskFields are the fields a task run fills in. They are accepted in any // workflow so a task workflow saves, and resolve empty where no task started // the run. var taskFields = map[string]bool{"review": true, "plan": true, "title": true, "body": true, "prompt": true, "repository": true, "kind": true, "issue": true, "pr": true} // refScope is what a step's references may read: the workflow's declared // inputs and the steps declared before it, each with the result fields its // type declares. A step whose type declares none has nil fields, and any // field of its result is accepted. type refScope struct { inputs map[string]bool steps map[string]map[string]bool } func newRefScope(inputs map[string]InputSpec) *refScope { scope := &refScope{inputs: map[string]bool{}, steps: map[string]map[string]bool{}} for name := range inputs { scope.inputs[name] = true } return scope } func (s *refScope) has(id string) bool { _, ok := s.steps[id] return ok } // stepIDPattern is narrower than a stable identifier: a step id is read inside // a dotted reference, so a dot in the id would make the reference ambiguous. var stepIDPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$`) // checkStepID requires a declared step id to be unique within the workflow and // readable inside a dotted reference. func checkStepID(id string, seen *refScope) error { if id == "" { return nil } if !stepIDPattern.MatchString(id) { return fmt.Errorf("step id %q must be lowercase letters and digits, joined by hyphens", id) } if seen.has(id) { return fmt.Errorf("step id %q is declared twice", id) } return nil } // checkReferences rejects a reference a run could not resolve: an unknown // root, an undeclared input, a step id that no earlier step declares, or a // result field that step's type does not declare. func checkReferences(settings yaml.Node, earlier *refScope) []error { var problems []error walkStrings(&settings, func(value string) { for _, match := range referencePattern.FindAllStringSubmatch(value, -1) { if err := checkReference(match[1], earlier); err != nil { problems = append(problems, err) } } }) return problems } func checkReference(path string, earlier *refScope) error { parts := strings.Split(path, ".") switch parts[0] { case "task", "inputs": if len(parts) < 2 { return fmt.Errorf("reference {{ %s }} names no field", path) } if parts[0] == "task" && !taskFields[parts[1]] { return fmt.Errorf("reference {{ %s }}: task has no field %q", path, parts[1]) } if parts[0] == "inputs" && !earlier.inputs[parts[1]] { return fmt.Errorf("reference {{ %s }}: the workflow declares no input %q", path, parts[1]) } return nil case "steps": return checkStepReference(path, parts, earlier) } return fmt.Errorf("reference {{ %s }} must start with task, inputs or steps", path) } // checkStepReference checks steps..summary and steps..result. // against the steps declared before the referencing one. func checkStepReference(path string, parts []string, earlier *refScope) error { if len(parts) < 3 { return fmt.Errorf("reference {{ %s }} must name a step and a field, e.g. steps.plan.summary", path) } if !earlier.has(parts[1]) { return fmt.Errorf("reference {{ %s }}: no earlier step has id %q", path, parts[1]) } if parts[2] != "summary" && parts[2] != "result" { return fmt.Errorf("reference {{ %s }}: a step exposes summary and result", path) } if fields := earlier.steps[parts[1]]; parts[2] == "result" && len(parts) > 3 && fields != nil && !fields[parts[3]] { return fmt.Errorf("reference {{ %s }}: step %q's result has no field %q", path, parts[1], parts[3]) } return nil } // scope is what a running step's references resolve against. func scope(inputs map[string]any, results map[string]StepResult) map[string]any { steps := make(map[string]any, len(results)) for id, r := range results { steps[id] = map[string]any{"summary": r.Summary, "result": r.Result} } if inputs == nil { inputs = map[string]any{} } return map[string]any{"task": map[string]any{}, "inputs": inputs, "steps": steps} } // renderSettings returns a copy of settings with every reference replaced by // its value in this run. // // A standalone reference preserves the value's type. References embedded in // strings are interpolated as text. Missing values render empty because a // skipped step produces no output. func renderSettings(settings yaml.Node, values map[string]any) yaml.Node { rendered := deepCopyNode(&settings) renderNode(rendered, values) return *rendered } // renderNode replaces references in a settings node's string values, in place. // Mapping keys are interpolated as text even for standalone references. func renderNode(node *yaml.Node, values map[string]any) { switch node.Kind { case yaml.DocumentNode, yaml.SequenceNode: for _, child := range node.Content { renderNode(child, values) } case yaml.MappingNode: for i := 0; i+1 < len(node.Content); i += 2 { interpolateNode(node.Content[i], values) renderNode(node.Content[i+1], values) } default: if node.Tag == "!!str" { renderValue(node, values) } } } // renderValue replaces one string value's references. A value that is exactly // one reference takes the referenced value's type; otherwise its references // are interpolated as text. func renderValue(node *yaml.Node, values map[string]any) { if match := soleReferencePattern.FindStringSubmatch(node.Value); match != nil { setNodeValue(node, lookupPath(values, match[1])) return } interpolateNode(node, values) } // interpolateNode replaces every reference in one string node with its text. func interpolateNode(node *yaml.Node, values map[string]any) { if node.Kind != yaml.ScalarNode || node.Tag != "!!str" { return } node.Value = referencePattern.ReplaceAllStringFunc(node.Value, func(token string) string { return stringify(lookupPath(values, referencePattern.FindStringSubmatch(token)[1])) }) } // setNodeValue replaces a scalar node with the node for value, so the value's // type survives the trip. An absent reference renders empty. A value yaml // cannot carry keeps the reference text, which reads better than dropping the // setting. func setNodeValue(node *yaml.Node, value any) { if value == nil { node.Value = "" return } raw, err := yaml.Marshal(value) if err != nil { return } var replacement yaml.Node if err := yaml.Unmarshal(raw, &replacement); err != nil { return } content := &replacement if replacement.Kind == yaml.DocumentNode && len(replacement.Content) == 1 { content = replacement.Content[0] } *node = *content } // lookupPath returns the value at a dotted path, or nil when there is none. func lookupPath(value any, path string) any { for key := range strings.SplitSeq(path, ".") { object, ok := value.(map[string]any) if !ok { return nil } value = object[key] } return value } func stringify(value any) string { switch v := value.(type) { case nil: return "" case string: return v default: encoded, err := json.Marshal(v, json.Deterministic(true)) if err != nil { return fmt.Sprint(v) } return string(encoded) } } // walkStrings visits every string scalar under node. func walkStrings(node *yaml.Node, visit func(string)) { if node.Kind == yaml.ScalarNode && node.Tag == "!!str" { visit(node.Value) } for _, child := range node.Content { walkStrings(child, visit) } } func deepCopyNode(node *yaml.Node) *yaml.Node { copied := *node copied.Content = make([]*yaml.Node, len(node.Content)) for i, child := range node.Content { copied.Content[i] = deepCopyNode(child) } return &copied }