Debian Codegraph @

internal/config/types/template.go

raw
1 package types
2
3 import (
4 "encoding/json"
5 "fmt"
6 "html/template"
7 "path"
8 )
9
10 type Template struct {
11 *template.Template
12
13 path string
14 }
15
16 func NewTemplate(filePath string) (Template, error) {
17 tmpl, err := template.New(path.Base(filePath)).ParseFiles(filePath)
18 if err != nil {
19 return Template{}, fmt.Errorf("failed to create template: %w", err)
20 }
21
22 return Template{tmpl, filePath}, nil
23 }
24
25 // IsEmpty checks if the template is empty.
26 //
27 //goland:noinspection GoMixedReceiverTypes
28 func (t *Template) IsEmpty() bool {
29 return t == nil || t.Template == nil
30 }
31
32 // String returns the path of the template.
33 //
34 //goland:noinspection GoMixedReceiverTypes
35 func (t *Template) String() string {
36 return t.path
37 }
38
39 // MarshalText implements the [encoding.TextMarshaler] interface.
40 //
41 //goland:noinspection GoMixedReceiverTypes
42 func (t Template) MarshalText() ([]byte, error) {
43 return []byte(t.String()), nil
44 }
45
46 // UnmarshalText implements the [encoding.TextUnmarshaler] interface.
47 //
48 //goland:noinspection GoMixedReceiverTypes
49 func (t *Template) UnmarshalText(text []byte) error {
50 tmpl, err := NewTemplate(string(text))
51 if err != nil {
52 return err
53 }
54
55 *t = tmpl
56
57 return nil
58 }
59
60 // MarshalJSON implements the [json.Marshaler] interface.
61 //
62 //goland:noinspection GoMixedReceiverTypes
63 func (t *Template) MarshalJSON() ([]byte, error) {
64 return json.Marshal(t.String()) //nolint:wrapcheck
65 }