templates.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package tpl
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "regexp"
  6. "slices"
  7. "strings"
  8. "text/template"
  9. "github.com/OliveTin/OliveTin/internal/entities"
  10. "github.com/OliveTin/OliveTin/internal/env"
  11. "github.com/OliveTin/OliveTin/internal/installationinfo"
  12. log "github.com/sirupsen/logrus"
  13. )
  14. func jsonFunc(v any) (string, error) {
  15. if v == nil {
  16. return "null", nil
  17. }
  18. data, err := json.Marshal(v)
  19. if err != nil {
  20. return "", err
  21. }
  22. return string(data), nil
  23. }
  24. // Root template (funcs/options). parseTemplate clones before Parse — text/template
  25. // must not receive concurrent Parse calls on the same instance.
  26. var tpl = template.New("tpl").
  27. Option("missingkey=error").
  28. Funcs(template.FuncMap{"Json": jsonFunc})
  29. type olivetinInfo struct {
  30. Build *installationinfo.BuildInfo
  31. Runtime *installationinfo.RuntimeInfo
  32. }
  33. var legacyArgumentRegex = regexp.MustCompile(`{{\s*([a-zA-Z0-9_]+)\s*}}`)
  34. var legacyEntityPropertiesRegex = regexp.MustCompile(`{{\s*([a-zA-Z0-9_]+)\.([a-zA-Z0-9_\.]+)\s*}}`)
  35. type generalTemplateContext struct {
  36. OliveTin olivetinInfo
  37. Env map[string]string
  38. }
  39. type actionTemplateContext struct {
  40. CurrentEntity any
  41. Arguments map[string]string
  42. // These are deliberately repeated because embedding structs
  43. // won't work in text/template.
  44. OliveTin olivetinInfo
  45. Env map[string]string
  46. }
  47. var (
  48. cachedOliveTinInfo olivetinInfo
  49. cachedEnvMap map[string]string
  50. )
  51. func init() {
  52. cachedOliveTinInfo = olivetinInfo{
  53. Build: installationinfo.Build,
  54. Runtime: installationinfo.Runtime,
  55. }
  56. cachedEnvMap = env.BuildEnvMap()
  57. }
  58. func GetNewGeneralTemplateContext() *generalTemplateContext {
  59. return &generalTemplateContext{
  60. OliveTin: cachedOliveTinInfo,
  61. Env: cachedEnvMap,
  62. }
  63. }
  64. func migrateLegacyEntityProperties(rawShellCommand string) string {
  65. foundArgumentNames := legacyEntityPropertiesRegex.FindAllStringSubmatch(rawShellCommand, -1)
  66. for _, match := range foundArgumentNames {
  67. entityName := match[1]
  68. argName := match[2]
  69. fullMatch := match[0] // The entire matched string like "{{ server.hostname }}"
  70. if strings.Contains(argName, ".") {
  71. replacement := "{{ .CurrentEntity." + argName + " }}"
  72. rawShellCommand = strings.ReplaceAll(rawShellCommand, fullMatch, replacement)
  73. log.WithFields(log.Fields{
  74. "old": entityName,
  75. "new": ".CurrentEntity",
  76. }).Debugf("Legacy entity variable name found, changing to CurrentEntity")
  77. continue
  78. }
  79. if !strings.HasPrefix(argName, ".Arguments.") {
  80. replacement := "{{ .CurrentEntity." + argName + " }}"
  81. rawShellCommand = strings.ReplaceAll(rawShellCommand, fullMatch, replacement)
  82. log.WithFields(log.Fields{
  83. "old": argName,
  84. "new": ".CurrentEntity." + argName,
  85. }).Debugf("Legacy variable name found, changing to CurrentEntity")
  86. }
  87. }
  88. return rawShellCommand
  89. }
  90. func migrateLegacyArgumentNames(rawShellCommand string) string {
  91. matches := legacyArgumentRegex.FindAllStringSubmatchIndex(rawShellCommand, -1)
  92. for _, match := range slices.Backward(matches) {
  93. fullMatchStart := match[0]
  94. fullMatchEnd := match[1]
  95. argNameStart := match[2]
  96. argNameEnd := match[3]
  97. argName := rawShellCommand[argNameStart:argNameEnd]
  98. log.WithFields(log.Fields{
  99. "old": argName,
  100. "new": ".Arguments." + argName,
  101. }).Debugf("Legacy variable name found, changing to Argument")
  102. replacement := "{{ .Arguments." + argName + " }}"
  103. rawShellCommand = rawShellCommand[:fullMatchStart] + replacement + rawShellCommand[fullMatchEnd:]
  104. }
  105. return rawShellCommand
  106. }
  107. func ParseTemplateWithActionContext(source string, ent *entities.Entity, args map[string]string) (string, error) {
  108. source = migrateLegacyArgumentNames(source)
  109. source = migrateLegacyEntityProperties(source)
  110. var entdata any
  111. if ent != nil {
  112. entdata = ent.Data
  113. }
  114. templateVariables := &actionTemplateContext{
  115. OliveTin: cachedOliveTinInfo,
  116. Env: cachedEnvMap,
  117. Arguments: args,
  118. CurrentEntity: entdata,
  119. }
  120. result, err := parseTemplate(source, templateVariables)
  121. if isMissingArgumentError, argName := checkMissingArgumentError(err); isMissingArgumentError {
  122. return "", fmt.Errorf("required arg not provided: %s", argName)
  123. }
  124. if err != nil {
  125. return "", err
  126. }
  127. return result, nil
  128. }
  129. func checkMissingArgumentError(err error) (bool, string) {
  130. if err == nil {
  131. return false, ""
  132. }
  133. if strings.Contains(err.Error(), "map has no entry for key") {
  134. re := regexp.MustCompile(`\.Arguments\.(\w+)`)
  135. match := re.FindStringSubmatch(err.Error())
  136. if len(match) > 1 {
  137. return true, match[1]
  138. }
  139. }
  140. return false, ""
  141. }
  142. func parseTemplate(source string, data any) (string, error) {
  143. clone, err := tpl.Clone()
  144. if err != nil {
  145. return "", err
  146. }
  147. t, err := clone.Parse(source)
  148. if err != nil {
  149. return "", err
  150. }
  151. var sb strings.Builder
  152. err = t.Execute(&sb, data)
  153. if err != nil {
  154. log.WithFields(log.Fields{
  155. "source": source,
  156. "err": err,
  157. }).Errorf("Error executing template")
  158. return "", err
  159. } else {
  160. return sb.String(), nil
  161. }
  162. }
  163. func ParseTemplateOfActionBeforeExec(source string, ent *entities.Entity) string {
  164. result, err := ParseTemplateWithActionContext(source, ent, nil)
  165. if err != nil {
  166. log.WithFields(log.Fields{
  167. "source": source,
  168. "err": err,
  169. }).Errorf("Error parsing template of action before exec")
  170. return ""
  171. }
  172. return result
  173. }
  174. // CheckActionTemplateParses migrates legacy template syntax and reports parse
  175. // errors only (execution against entity/argument data is not attempted).
  176. func CheckActionTemplateParses(source string) error {
  177. if source == "" {
  178. return nil
  179. }
  180. source = migrateLegacyArgumentNames(source)
  181. source = migrateLegacyEntityProperties(source)
  182. clone, err := tpl.Clone()
  183. if err != nil {
  184. return err
  185. }
  186. _, err = clone.Parse(source)
  187. return err
  188. }
  189. /*
  190. func ParseTemplateBoolWith(source string, ent *entities.Entity) bool {
  191. source = strings.TrimSpace(source)
  192. tplBool := ParseTemplateOfActionBeforeExec(source, ent)
  193. return tplBool == "true"
  194. }
  195. */