|
| 1 | +// This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | +// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | +// file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 4 | + |
| 5 | +package action |
| 6 | + |
| 7 | +import ( |
| 8 | + "bytes" |
| 9 | + "maps" |
| 10 | + "strconv" |
| 11 | + "strings" |
| 12 | + "text/template" |
| 13 | + |
| 14 | + "github.com/stretchr/testify/require" |
| 15 | + |
| 16 | + "github.com/sourcenetwork/lens/tests/state" |
| 17 | +) |
| 18 | + |
| 19 | +// templateDataGenerators contains a set of data generators by their template prefix. |
| 20 | +// |
| 21 | +// Supporting action properties will replace any templated elements with data drawn from these |
| 22 | +// sets. |
| 23 | +var templateDataGenerators = map[string]func(*state.State) map[string]string{ |
| 24 | + "LensIDs": func(s *state.State) map[string]string { |
| 25 | + res := map[string]string{} |
| 26 | + for i, ID := range s.LensIDs { |
| 27 | + res["LensIDs"+strconv.Itoa(i)] = ID.String() |
| 28 | + } |
| 29 | + |
| 30 | + return res |
| 31 | + }, |
| 32 | +} |
| 33 | + |
| 34 | +// replace returns a new string with any templating placholders (see "text/template") with data drawn |
| 35 | +// from `state`. |
| 36 | +func replace(s *state.State, input string) string { |
| 37 | + if !strings.Contains(input, "{{") { |
| 38 | + // If the input doesn't contain any templating elements we can return early |
| 39 | + return input |
| 40 | + } |
| 41 | + |
| 42 | + templateData := map[string]string{} |
| 43 | + for _, datasetGenerator := range templateDataGenerators { |
| 44 | + // Having to regenerate the full dataset for every node-action is horribly inefficient, but |
| 45 | + // it is tolerable for now. |
| 46 | + maps.Copy(templateData, datasetGenerator(s)) |
| 47 | + } |
| 48 | + |
| 49 | + tmpl := template.Must(template.New("").Parse(input)) |
| 50 | + var buf bytes.Buffer |
| 51 | + err := tmpl.Execute(&buf, templateData) |
| 52 | + require.NoError(s.T, err) |
| 53 | + |
| 54 | + return buf.String() |
| 55 | +} |
0 commit comments