2022-07-18 00:56:09 +00:00
|
|
|
package templates
|
|
|
|
|
|
|
|
import (
|
2022-08-26 21:39:20 +00:00
|
|
|
"bytes"
|
2022-07-18 00:56:09 +00:00
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"path/filepath"
|
|
|
|
"text/template"
|
|
|
|
)
|
|
|
|
|
2022-08-26 21:39:20 +00:00
|
|
|
func tmplEnvelopeHasDeprecatedPlaceholders(data []byte) bool {
|
|
|
|
return bytes.Contains(data, []byte("{{ .Boundary }}")) ||
|
|
|
|
bytes.Contains(data, []byte("{{ .Body.PlainText }}")) ||
|
|
|
|
bytes.Contains(data, []byte("{{ .Body.HTML }}"))
|
|
|
|
}
|
|
|
|
|
2022-07-18 00:56:09 +00:00
|
|
|
func templateExists(path string) (exists bool) {
|
|
|
|
info, err := os.Stat(path)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
if info.IsDir() {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2022-08-26 21:39:20 +00:00
|
|
|
func readTemplate(name, category, overridePath string) (tPath string, embed bool, data []byte, err error) {
|
2022-07-18 00:56:09 +00:00
|
|
|
if overridePath != "" {
|
2022-08-26 21:39:20 +00:00
|
|
|
tPath = filepath.Join(overridePath, name)
|
2022-07-18 00:56:09 +00:00
|
|
|
|
|
|
|
if templateExists(tPath) {
|
2022-08-26 21:39:20 +00:00
|
|
|
if data, err = os.ReadFile(tPath); err != nil {
|
|
|
|
return tPath, false, nil, fmt.Errorf("failed to read template override at path '%s': %w", tPath, err)
|
2022-07-18 00:56:09 +00:00
|
|
|
}
|
|
|
|
|
2022-08-26 21:39:20 +00:00
|
|
|
return tPath, false, data, nil
|
2022-07-18 00:56:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-26 21:39:20 +00:00
|
|
|
tPath = path.Join("src", category, name)
|
|
|
|
|
|
|
|
if data, err = embedFS.ReadFile(tPath); err != nil {
|
|
|
|
return tPath, true, nil, fmt.Errorf("failed to read embedded template '%s': %w", tPath, err)
|
2022-07-18 00:56:09 +00:00
|
|
|
}
|
|
|
|
|
2022-08-26 21:39:20 +00:00
|
|
|
return tPath, true, data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseTemplate(name, tPath string, embed bool, data []byte) (t *template.Template, err error) {
|
2022-07-18 00:56:09 +00:00
|
|
|
if t, err = template.New(name).Parse(string(data)); err != nil {
|
2022-08-26 21:39:20 +00:00
|
|
|
if embed {
|
|
|
|
return nil, fmt.Errorf("failed to parse embedded template '%s': %w", tPath, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, fmt.Errorf("failed to parse template override at path '%s': %w", tPath, err)
|
2022-07-18 00:56:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return t, nil
|
|
|
|
}
|
2022-08-26 21:39:20 +00:00
|
|
|
|
|
|
|
//nolint:unparam
|
|
|
|
func loadTemplate(name, category, overridePath string) (t *template.Template, err error) {
|
|
|
|
var (
|
|
|
|
embed bool
|
|
|
|
tPath string
|
|
|
|
data []byte
|
|
|
|
)
|
|
|
|
|
|
|
|
if tPath, embed, data, err = readTemplate(name, category, overridePath); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return parseTemplate(name, tPath, embed, data)
|
|
|
|
}
|