|
1 | 1 | package utils |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "fmt" |
5 | | - "reflect" |
6 | | - "regexp" |
| 4 | + "bytes" |
| 5 | + "text/template" |
7 | 6 | ) |
8 | 7 |
|
9 | | -func getQuotedAddressRegexExpressionReplacer(contractName string) string { |
10 | | - const regexPattern = `"(?:(?:\./|(?:\.\./)+)?(?:[a-zA-Z0-9_\-]+/)*%s(\.cdc)?)"` |
11 | | - return fmt.Sprintf(regexPattern, contractName) |
12 | | -} |
13 | | - |
14 | | -func getRegexExpressionReplacer(contractName string) string { |
15 | | - const regexPattern = `%s` |
16 | | - return fmt.Sprintf(regexPattern, contractName) |
17 | | -} |
18 | | - |
19 | 8 | // ParseCadenceTemplate parses the Cadence template and replaces placeholders |
20 | | -func ParseCadenceTemplate(template []byte, data ...interface{}) ([]byte, error) { |
21 | | - if err := validateStruct(data); err != nil { |
22 | | - return nil, err |
23 | | - } |
24 | | - updatedTemplate, err := replacePlaceholders(string(template), data) |
| 9 | +func ParseCadenceTemplate(tmp []byte, data interface{}) ([]byte, error) { |
| 10 | + tmpl, err := template.New("Template").Parse(string(tmp)) |
25 | 11 | if err != nil { |
26 | 12 | return nil, err |
27 | 13 | } |
28 | 14 |
|
29 | | - return []byte(updatedTemplate), nil |
30 | | -} |
31 | | - |
32 | | -// validateStruct ensures the provided data is a struct |
33 | | -func validateStruct(data []interface{}) error { |
34 | | - for _, item := range data { |
35 | | - if item == nil { |
36 | | - continue |
37 | | - } |
38 | | - if reflect.ValueOf(item).Kind() != reflect.Struct { |
39 | | - return fmt.Errorf("data must be a struct") |
40 | | - } |
41 | | - } |
42 | | - return nil |
43 | | -} |
44 | | - |
45 | | -// replacePlaceholders replaces the placeholders in the template with actual values |
46 | | -func replacePlaceholders(template string, data []interface{}) (string, error) { |
47 | | - for index, item := range data { |
48 | | - if item == nil { |
49 | | - continue |
50 | | - } |
51 | | - val := reflect.ValueOf(item) |
52 | | - for i := 0; i < val.NumField(); i++ { |
53 | | - field := val.Type().Field(i) |
54 | | - fieldName := field.Name |
55 | | - fieldValue := val.Field(i).String() |
56 | | - if index == 0 { |
57 | | - replacer := regexp.MustCompile(getQuotedAddressRegexExpressionReplacer(fieldName)) |
58 | | - template = replacer.ReplaceAllString(template, "0x"+fieldValue) |
59 | | - } else { |
60 | | - replacer := regexp.MustCompile(getRegexExpressionReplacer(fieldName)) |
61 | | - template = replacer.ReplaceAllString(template, fieldValue) |
62 | | - } |
63 | | - } |
64 | | - |
| 15 | + buf := &bytes.Buffer{} |
| 16 | + err = tmpl.Execute(buf, data) |
| 17 | + if err != nil { |
| 18 | + return nil, err |
65 | 19 | } |
66 | 20 |
|
67 | | - return template, nil |
| 21 | + return buf.Bytes(), nil |
68 | 22 | } |
0 commit comments