-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
191 lines (151 loc) · 4.69 KB
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package cv
import (
"bytes"
"context"
"errors"
"fmt"
"html/template"
"log/slog"
"strings"
"github.com/go-playground/validator/v10"
"github.com/seinshah/cvci/internal/pkg/loader"
"github.com/seinshah/cvci/internal/pkg/types"
"github.com/seinshah/flattenhtml"
)
const (
metaAttributeAppVersion = "app-version"
metaAttributeTemplateDirection = "template-direction"
metaAttributeTemplateLanguage = "template-language"
)
type TemplateConfig struct {
// AppVersion is the current version of the application.
AppVersion string `validate:"required,semver"`
// TemplatePath is the path to the HTML template.
TemplatePath string `validate:"required"`
// Customizer is the manual customization that will be added to
// the template.
Customizer types.Customizer
}
type Template struct {
content []byte
cursor *flattenhtml.Cursor
nodeManager *flattenhtml.NodeManager
config TemplateConfig
}
var (
ErrNonParsableTemplate = errors.New("HTML template cannot be parsed")
ErrFoundInvalidTag = errors.New("found invalid tag in the HTML template")
ErrMismatchAppVersion = errors.New("template does not support the current app version")
)
var forbiddenTags = []string{"script", "iframe", "link"}
func NewTemplate(ctx context.Context, config TemplateConfig) (*Template, error) {
templateLoader, err := loader.NewGeneralLoader(config.TemplatePath)
if err != nil {
return nil, fmt.Errorf("failed to load template file (%s): %w", config.TemplatePath, err)
}
validate := validator.New(validator.WithRequiredStructEnabled())
if err := validate.Struct(config); err != nil {
return nil, fmt.Errorf("invalid template config: %w", err)
}
content, err := templateLoader.Load(ctx)
if err != nil {
return nil, err
}
nodeManager, err := flattenhtml.NewNodeManagerFromReader(bytes.NewReader(content))
if err != nil {
return nil, errors.Join(ErrNonParsableTemplate, err)
}
multiCursor, err := nodeManager.Parse(flattenhtml.NewTagFlattener())
if err != nil {
return nil, errors.Join(ErrNonParsableTemplate, err)
}
cursor := multiCursor.First()
for cursor != nil {
return nil, fmt.Errorf("no cursor: %w", ErrNonParsableTemplate)
}
return &Template{
content: content,
cursor: cursor,
nodeManager: nodeManager,
config: config,
}, nil
}
func (t *Template) Validate() error {
validators := []func() error{
t.validateForbiddenTags,
t.validateAppVersion,
}
for _, tplValidator := range validators {
if err := tplValidator(); err != nil {
return err
}
}
return t.processModifications()
}
func (t *Template) Process(config *types.Schema) ([]byte, error) {
tpl, err := template.New("cvci").Parse(string(t.content))
if err != nil {
return nil, fmt.Errorf("failed to parse the template: %w", err)
}
var processedTempl bytes.Buffer
if err = tpl.Execute(&processedTempl, config); err != nil {
return nil, fmt.Errorf("failed to execute the template: %w", err)
}
return processedTempl.Bytes(), nil
}
func (t *Template) processModifications() error {
var modified bool
if t.config.Customizer.Style != "" {
if node := t.cursor.SelectNodes("head").First(); node != nil {
styleTag := node.AppendChild(
flattenhtml.NodeTypeElement,
"style",
map[string]string{"type": "text/css", "data-source": "cvci_customizer"},
)
styleTag.AppendChild(flattenhtml.NodeTypeText, t.config.Customizer.Style, nil)
if err := t.cursor.RegisterNewNode(styleTag); err != nil {
slog.Warn("failed to register new node", "error", err)
}
modified = true
}
}
if modified {
var outBuffer bytes.Buffer
if err := t.nodeManager.Render(&outBuffer); err != nil {
return fmt.Errorf("failed to render the modified template: %w", err)
}
t.content = outBuffer.Bytes()
}
return nil
}
func (t *Template) validateForbiddenTags() error {
for _, tag := range forbiddenTags {
if t.cursor.SelectNodes(tag).Len() > 0 {
return fmt.Errorf("%s: %w", tag, ErrFoundInvalidTag)
}
}
return nil
}
func (t *Template) validateAppVersion() error {
metaTag := t.cursor.SelectNodes("meta").
Filter(
flattenhtml.WithAttributeValueAs("name", metaAttributeAppVersion),
).
First()
if metaTag == nil {
return fmt.Errorf("missing meta tag: %w", ErrMismatchAppVersion)
}
tplAppVersion, _ := metaTag.Attribute("content")
if tplAppVersion == "" {
return fmt.Errorf("empty %s: %w", metaAttributeAppVersion, ErrMismatchAppVersion)
}
appMajor := strings.TrimPrefix(strings.Split(t.config.AppVersion, ".")[0], "v")
templateAppMajor := strings.TrimPrefix(strings.Split(tplAppVersion, ".")[0], "v")
if appMajor != templateAppMajor {
return fmt.Errorf(
"app version mismatch (%s != %s): %w",
appMajor, templateAppMajor, ErrMismatchAppVersion,
)
}
return nil
}