|
| 1 | +package workflows |
| 2 | + |
| 3 | +import ( |
| 4 | + "cmp" |
| 5 | + "fmt" |
| 6 | + "maps" |
| 7 | + "slices" |
| 8 | + "strings" |
| 9 | + "text/template" |
| 10 | + |
| 11 | + "github.com/smartcontractkit/chainlink-common/pkg/capabilities" |
| 12 | + "github.com/smartcontractkit/chainlink-common/pkg/workflows/sdk" |
| 13 | +) |
| 14 | + |
| 15 | +func (g *DependencyGraph) FormatChart() (string, error) { |
| 16 | + var sb strings.Builder |
| 17 | + steps := slices.Clone(g.Spec.Triggers) |
| 18 | + steps = append(steps, g.Spec.Steps()...) |
| 19 | + slices.SortFunc(steps, func(a, b sdk.StepDefinition) int { |
| 20 | + return cmp.Or( |
| 21 | + a.CapabilityType.Compare(b.CapabilityType), |
| 22 | + cmp.Compare(a.Ref, b.Ref), |
| 23 | + cmp.Compare(a.ID, b.ID), |
| 24 | + ) |
| 25 | + }) |
| 26 | + preds, err := g.Graph.PredecessorMap() |
| 27 | + if err != nil { |
| 28 | + return "", fmt.Errorf("failed to get graph predecessors: %w", err) |
| 29 | + } |
| 30 | + type stepAndOutput struct { |
| 31 | + Step sdk.StepDefinition |
| 32 | + Inputs []string |
| 33 | + } |
| 34 | + nodes := make([]stepAndOutput, len(steps)) |
| 35 | + for i, step := range steps { |
| 36 | + inputs := slices.Collect(maps.Keys(preds[step.Ref])) |
| 37 | + if step.CapabilityType != capabilities.CapabilityTypeTrigger { |
| 38 | + inputs = append(inputs, KeywordTrigger) |
| 39 | + } |
| 40 | + slices.Sort(inputs) |
| 41 | + nodes[i] = stepAndOutput{Step: step, Inputs: inputs} |
| 42 | + } |
| 43 | + err = tmpl.Execute(&sb, nodes) |
| 44 | + if err != nil { |
| 45 | + return "", err |
| 46 | + } |
| 47 | + return sb.String(), nil |
| 48 | +} |
| 49 | + |
| 50 | +var tmpl = template.Must(template.New("").Funcs(map[string]any{ |
| 51 | + "replace": strings.ReplaceAll, |
| 52 | +}).Parse(`flowchart |
| 53 | +{{ range $i, $e := . }} |
| 54 | + {{ $ref := .Step.Ref -}} |
| 55 | + {{ $id := replace .Step.ID "@" "[at]" -}} |
| 56 | + {{ $name := printf "%s<br><i>(%s)</i>" .Step.CapabilityType $id -}} |
| 57 | + {{ if .Step.Ref -}} |
| 58 | + {{ $name = printf "<b>%s</b><br>%s" .Step.Ref $name -}} |
| 59 | + {{ else -}} |
| 60 | + {{ $ref = printf "%s%d" "unnamed" $i -}} |
| 61 | + {{ end -}} |
| 62 | + {{ if eq .Step.CapabilityType "trigger" -}} |
| 63 | + {{ $ref }}[\"{{$name}}"/] |
| 64 | + {{ else if eq .Step.CapabilityType "consensus" -}} |
| 65 | + {{ $ref }}[["{{$name}}"]] |
| 66 | + {{ else if eq .Step.CapabilityType "target" -}} |
| 67 | + {{ $ref }}[/"{{$name}}"\] |
| 68 | + {{ else -}} |
| 69 | + {{ $ref }}["{{$name}}"] |
| 70 | + {{ end -}} |
| 71 | + {{ if .Step.Inputs.OutputRef -}} |
| 72 | + {{ .Step.Inputs.OutputRef }} --> {{ .Step.Ref }} |
| 73 | + {{ else -}} |
| 74 | + {{ range $out := .Inputs -}} |
| 75 | + {{ $out }} --> {{ $ref }} |
| 76 | + {{ end -}} |
| 77 | + {{ end -}} |
| 78 | +{{ end -}} |
| 79 | +`)) |
0 commit comments