-
Notifications
You must be signed in to change notification settings - Fork 0
/
funi.go
74 lines (59 loc) · 1.24 KB
/
funi.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
package funi
import (
"encoding/json"
"io"
"os"
"gopkg.in/yaml.v2"
)
// Options is option for rendering
type Options struct {
Format string
InputPath string
OutputPath string
TemplateString string
}
func loadInputFile(path string, r io.ReadCloser) (io.ReadCloser, error) {
var inFile io.ReadCloser
var err error
if path == "" {
inFile = r
} else {
inFile, err = os.Open(path)
}
return inFile, err
}
func openOutputFile(path string, w io.WriteCloser) (io.WriteCloser, error) {
var outFile io.WriteCloser
var err error
if path == "" {
outFile = w
} else {
outFile, err = os.Create(path)
}
return outFile, err
}
// Render renders template
func Render(opts Options) error {
renderer, err := NewRenderer(opts.TemplateString)
if err != nil {
return err
}
inFile, err := loadInputFile(opts.InputPath, os.Stdin)
if err != nil {
return err
}
defer inFile.Close()
outFile, err := openOutputFile(opts.OutputPath, os.Stdout)
if err != nil {
return err
}
defer outFile.Close()
var unmarshalFunc func([]byte, interface{}) error
switch opts.Format {
case "json":
unmarshalFunc = json.Unmarshal
case "yaml":
unmarshalFunc = yaml.Unmarshal
}
return renderer.execute(inFile, outFile, unmarshalFunc)
}