-
Notifications
You must be signed in to change notification settings - Fork 0
/
modgen.go
90 lines (73 loc) · 1.74 KB
/
modgen.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
package modgen
import (
"bytes"
"html/template"
"os"
"path"
)
// Generator contains the context required to generate a Go module import URL static site.
type Generator struct {
config Config
indexTmpl *template.Template
moduleTmpl *template.Template
}
func NewGenerator(config Config) *Generator {
return &Generator{
config: config,
indexTmpl: indexTmpl,
moduleTmpl: moduleTmpl,
}
}
func (g *Generator) WithIndexTemplate(path string) error {
raw, err := os.ReadFile(path)
if err != nil {
return err
}
tmpl, err := template.New("index-custom").Parse(string(raw))
if err != nil {
return err
}
g.indexTmpl = tmpl
return nil
}
func (g *Generator) WithModuleTemplate(path string) error {
raw, err := os.ReadFile(path)
if err != nil {
return err
}
tmpl, err := template.New("module-custom").Parse(string(raw))
if err != nil {
return err
}
g.moduleTmpl = tmpl
return nil
}
func (g *Generator) Generate(target string) error {
if err := os.MkdirAll(target, 0755); err != nil {
return err
}
if err := g.generateIndex(path.Join(target, "index.html")); err != nil {
return err
}
for _, module := range g.config.Modules {
modulePath := path.Join(target, module.Path+".html")
if err := g.generateModule(modulePath, module); err != nil {
return err
}
}
return nil
}
func (g *Generator) generateIndex(target string) error {
b := bytes.Buffer{}
if err := g.indexTmpl.Execute(&b, g.config); err != nil {
return err
}
return os.WriteFile(target, b.Bytes(), 0644)
}
func (g *Generator) generateModule(target string, module ModuleConfig) error {
b := bytes.Buffer{}
if err := g.moduleTmpl.Execute(&b, module.withHost(g.config.Host)); err != nil {
return err
}
return os.WriteFile(target, b.Bytes(), 0644)
}