-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
323 lines (282 loc) · 8.78 KB
/
config.go
File metadata and controls
323 lines (282 loc) · 8.78 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
package main
// This file sets all of the configuration related items in the project,
// particularly in relation to config.yaml but also how items are
// represented in the resulting html pages. Validation of each described
// "page" and its related clickable zones are performed here.
import (
"bytes"
"embed"
"errors"
"fmt"
"html/template"
"io/fs"
"os"
"path/filepath"
"github.com/goccy/go-yaml"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/renderer/html"
)
// ErrInvalidConfig reports an invalid yaml configuration file, although
// one that passed parsing.
type ErrInvalidConfig struct {
info string
}
// Error reports the error.
func (e ErrInvalidConfig) Error() string {
return fmt.Sprintf("invalid config or template: %s", e.info)
}
const (
AssetDirName = "assets" // TODO: fix to work with runtime path
ConfigFileName = "config.yaml" // TODO: fix to work with supplied config file
)
var RequiredAssetDirs []string = []string{
"templates",
"static",
"images",
}
// md is a markdown goldmark instance using GFM (github markdown) and
// safety settings (called WithUnsafe).
var md = goldmark.New(
goldmark.WithExtensions(extension.GFM),
goldmark.WithRendererOptions(
html.WithUnsafe(),
),
)
// Embedded file systems and files
//
//go:embed assets
var assetsFS embed.FS
//go:embed config.yaml
var configYaml []byte
// config describes the config in a yaml configuration file
type config struct {
PageTemplate string `yaml:"pageTemplate"`
IndexTemplate string `yaml:"indexTemplate"`
Pages []page `yaml:"pages"`
// Assets path (for image, template and static directories) and
// associated fs.FS
AssetsDir string `yaml:"assetsDir"`
AssetsFS fs.FS
// html templates
PageTpl *template.Template
IndexTpl *template.Template
pagesByURL map[string]int
embeddedMode bool
}
// validateConfig validates the configuration and also sets fields such
// as the filesystems (ImageFS, etc).
func (c *config) validateConfig() error {
// Attach the filesystems. Beware that embedded filesystems need to
// be attached below a named container to match the behaviour of
// os.DirFS.
if c.embeddedMode {
var err error
c.AssetsFS, err = fs.Sub(assetsFS, AssetDirName)
if err != nil {
return ErrInvalidConfig{fmt.Sprintf("could not mount embedded fs: %v", err)}
}
} else {
if !dirExists(c.AssetsDir) {
return ErrInvalidConfig{fmt.Sprintf("directory %q does not exist", c.AssetsDir)}
}
c.AssetsFS = os.DirFS(c.AssetsDir)
}
// Check the required directories in the AssetsFS
dir, err := fs.ReadDir(c.AssetsFS, ".")
if err != nil {
return fmt.Errorf("internal error: could not read filesystem: %v", err)
}
OUTER:
for _, req := range RequiredAssetDirs {
for _, item := range dir {
if req == item.Name() && item.Type().IsDir() {
continue OUTER
}
}
return fmt.Errorf("required directory %q not found in filesystem", req)
}
if c.PageTpl, err = template.ParseFS(c.AssetsFS, c.PageTemplate); err != nil {
return ErrInvalidConfig{fmt.Sprintf("pageTemplate parsing error: %v", err)}
}
if c.IndexTpl, err = template.ParseFS(c.AssetsFS, c.IndexTemplate); err != nil {
return ErrInvalidConfig{fmt.Sprintf("indexTemplate parsing error: %v", err)}
}
// Ensure at least two pages are defined.
if len(c.Pages) < 2 {
return ErrInvalidConfig{"at least two pages must be defined"}
}
// Register of page and zone urls to ensure that the latter only
// call out valid pages. Note that the context of a page is stored
// in the zoneURLMap value and if multiple incorrect Zone Target
// values are used with the same URL the last will be reported.
c.pagesByURL = map[string]int{}
for ii, pg := range c.Pages {
if pg.URL == "" {
return ErrInvalidConfig{fmt.Sprintf("url empty for page %d (%s)", ii, pg.Title)}
}
if pg.Title == "" {
return ErrInvalidConfig{fmt.Sprintf("title empty for page %d (%s)", ii, pg.URL)}
}
if pg.ImagePath == "" {
return ErrInvalidConfig{fmt.Sprintf("image path empty for page %d (%s)", ii, pg.Title)}
}
if len(pg.Zones) < 1 {
return ErrInvalidConfig{fmt.Sprintf("no zones defined for page %d (%s)", ii, pg.Title)}
}
if c.hasURL(pg.URL) {
return ErrInvalidConfig{fmt.Sprintf("URL for page %d (%s) already exists", ii, pg.URL)}
}
c.pagesByURL[pg.URL] = ii
// Note processing
if pg.Note == "" {
continue
}
var buf bytes.Buffer
if err := md.Convert([]byte(pg.Note), &buf); err != nil {
return fmt.Errorf("error processing markdown for page %q: %w", pg.URL, err)
}
c.Pages[ii].NoteHTML = template.HTML(buf.String())
}
for ii, pg := range c.Pages {
for zi, zo := range pg.Zones {
if zo.Target == "" {
return ErrInvalidConfig{fmt.Sprintf(
"page %d zone %d empty 'Target' value",
ii, zi,
)}
}
if zo.Right < zo.Left || zo.Right == 0 {
return ErrInvalidConfig{fmt.Sprintf(
"page %d zone %d invalid 'Right' value of %d",
ii, zi, zo.Right,
)}
}
if zo.Bottom < zo.Top || zo.Bottom == 0 {
return ErrInvalidConfig{fmt.Sprintf(
"page %d zone %d invalid 'Bottom' value of %d",
ii, zi, zo.Bottom,
)}
}
pgIdx, ok := c.pagesByURL[zo.Target]
if !ok {
return ErrInvalidConfig{fmt.Sprintf(
"invalid Zone Target URL %s for page %s (%d) zone %d",
zo.Target,
pg.Title,
ii,
zi,
)}
}
c.Pages[ii].Zones[zi].TargetTitle = c.Pages[pgIdx].Title
}
}
return nil
}
// hasURL determines if url is in the pages URL field.
func (c *config) hasURL(s string) bool {
_, ok := c.pagesByURL[s]
return ok
}
// newConfig creates and validates a new config from reading a yaml
// file, initialising in embedded mode or not.
func newConfig(b []byte, embeddedMode bool) (*config, error) {
var c config
if err := yaml.Unmarshal(b, &c); err != nil {
return nil, fmt.Errorf("unmarshal error: %v", err)
}
c.embeddedMode = embeddedMode
err := c.validateConfig()
return &c, err
}
// pageZone sets up a rectangular page zone on a page that, when
// clicked, redirects to Target.
type pageZone struct {
Left int `yaml:"Left"`
Top int `yaml:"Top"`
Right int `yaml:"Right"`
Bottom int `yaml:"Bottom"`
Target string `yaml:"Target"`
TargetTitle string // determined in processing
}
// Width returns the width of the pageZone.
func (p *pageZone) Width() int {
return p.Right - p.Left
}
// Height returns the height of the pageZone.
func (p *pageZone) Height() int {
return p.Bottom - p.Top
}
// page is a web page represented by an image located at URL, holding 0
// or more Zones which, when clicked, redirect to the page in question.
type page struct {
URL string `yaml:"URL"`
Title string `yaml:"Title"`
ImagePath string `yaml:"ImagePath"`
Note string `yaml:"Note,omitempty"`
Zones []pageZone `yaml:"Zones"`
// Markdown content from Note.
NoteHTML template.HTML
}
// dirExists checks if the path is to a valid directory.
func dirExists(path string) bool {
s, err := os.Stat(path)
if err != nil {
return false
}
if !s.IsDir() {
return false
}
return true
}
// WriteAssets writes the embedded assets described in the config to
// disk.
func WriteAssets(c *config, savePath string) error {
if !dirExists(savePath) {
return fmt.Errorf("directory %s does not exist", savePath)
}
if !c.embeddedMode {
return errors.New("write assets only permitted for embedded mode")
}
// Check if the target directory or config files exists
assetFP := filepath.Join(savePath, AssetDirName)
if _, err := os.Stat(assetFP); err == nil {
return fmt.Errorf("target directory %q already exists", assetFP)
}
configFP := filepath.Join(savePath, ConfigFileName)
if _, err := os.Stat(configFP); err == nil {
return fmt.Errorf("config file %q already exists", configFP)
}
// For each embedded FS, write its contents to the corresponding
// target directory.
err := writeFSToDisk(assetFP, c.AssetsFS)
if err != nil {
return fmt.Errorf("error writing %s: %w", AssetDirName, err)
}
return os.WriteFile(configFP, configYaml, 0644)
}
// writeFSToDisk walks an embed.FS and writes its contents to a physical
// directory on disk.
func writeFSToDisk(destRoot string, sourceFS fs.FS) error {
return fs.WalkDir(sourceFS, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err // propogate errors
}
// Destination on disk.
destPath := filepath.Join(destRoot, path)
if d.IsDir() {
// os.MkdirAll is idempotent.
return os.MkdirAll(destPath, 0755)
}
// For files read the content from the virtual file system.
fileBytes, err := fs.ReadFile(sourceFS, path)
if err != nil {
return fmt.Errorf("could not read embedded file %s: %w", path, err)
}
// Write the file to the physical disk.
if err := os.WriteFile(destPath, fileBytes, 0644); err != nil {
return fmt.Errorf("could not write file to %s: %w", destPath, err)
}
return nil
})
}