-
Notifications
You must be signed in to change notification settings - Fork 3
/
tmpl.go
79 lines (67 loc) · 1.87 KB
/
tmpl.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
// Package tmpl implements template generation and variable substition from a large set of data locations
package tmpl
import (
"errors"
"fmt"
)
// Tmpl is a facade for the template generation process. It creates (partially best guesses)
type Tmpl struct {
Data Location
Decoder Decoder
Renderer Renderer
Template Location
}
// Build constructs the Tmpl facade from names of components
func Build(dataLocation, decoderName, templateLocation, rendererName string) (*Tmpl, error) {
if dataLocation == "-" && dataLocation == templateLocation {
return nil, errors.New("cannot use STDIN for data and template at the same time")
}
data, err := GuessLocation(dataLocation)
if err != nil {
return nil, fmt.Errorf("failed to create data location: %w", err)
}
var decoder Decoder
if decoderName == "guess" {
decoder, err = GuessDecoder(dataLocation)
} else {
decoder, err = BuildDecoder(decoderName)
}
if err != nil {
return nil, fmt.Errorf("failed to create data decoder: %w", err)
}
template, err := GuessLocation(templateLocation)
if err != nil {
return nil, fmt.Errorf("failed to create template location: %w", err)
}
var renderer Renderer
if rendererName == "guess" {
renderer, err = GuessRenderer(templateLocation)
} else {
renderer, err = BuildRenderer(rendererName)
}
if err != nil {
return nil, fmt.Errorf("failed to create renderer: %w", err)
}
return &Tmpl{
Data: data,
Decoder: decoder,
Template: template,
Renderer: renderer,
}, nil
}
// Produce reads & decodes the data, loads the template and returns the rendered result
func (q *Tmpl) Produce() ([]byte, error) {
data, err := q.Data.Load()
if err != nil {
return nil, err
}
decoded, err := q.Decoder.Decode(data)
if err != nil {
return nil, err
}
template, err := q.Template.Load()
if err != nil {
return nil, err
}
return q.Renderer.Render(decoded, template)
}