-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtemplate.go
70 lines (59 loc) · 1.64 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
package golang
import (
"fmt"
"strings"
"github.com/samber/lo"
"projectforge.dev/projectforge/app/file"
"projectforge.dev/projectforge/app/lib/filesystem"
"projectforge.dev/projectforge/app/util"
)
type Template struct {
Path []string `json:"path,omitempty"`
Name string `json:"name"`
Imports Imports `json:"imports"`
Blocks Blocks `json:"blocks"`
}
func NewGoTemplate(path []string, fn string) *Template {
return &Template{Path: path, Name: fn}
}
func (f *Template) AddImport(i ...*Import) {
lo.ForEach(i, func(imp *Import, _ int) {
hit := lo.ContainsBy(f.Imports, func(x *Import) bool {
return x.Equals(imp)
})
if !hit {
f.Imports = append(f.Imports, imp)
}
})
}
func (f *Template) AddBlocks(b ...*Block) {
f.Blocks = append(f.Blocks, b...)
}
func (f *Template) Render(addHeader bool, linebreak string) (*file.File, error) {
var content []string
add := func(s string, args ...any) {
content = append(content, fmt.Sprintf(s+linebreak, args...))
}
if addHeader {
switch {
case strings.HasSuffix(f.Name, util.ExtSQL):
content = append(content, fmt.Sprintf("-- %s", file.HeaderContent))
case strings.HasSuffix(f.Name, ".graphql"):
content = append(content, fmt.Sprintf("# %s", file.HeaderContent))
default:
content = append(content, fmt.Sprintf("<!-- %s -->", file.HeaderContent))
}
}
if len(f.Imports) > 0 {
add(f.Imports.RenderHTML(linebreak))
}
for _, b := range f.Blocks {
x, err := b.Render(linebreak)
if err != nil {
return nil, err
}
add(x)
}
n := f.Name
return &file.File{Path: f.Path, Name: n, Mode: filesystem.DefaultMode, Content: strings.Join(content, linebreak)}, nil
}