forked from bitnami/render-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd.go
69 lines (61 loc) · 1.72 KB
/
cmd.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
package main
import (
"fmt"
"io"
"os"
)
// RenderTemplateCmd allows rendering templates
type RenderTemplateCmd struct {
DataFile string `short:"f" long:"data-file" description:"Properties file containing the replacements for the template" value-name:"DATA_FILE"`
Args struct {
TemplateFile string `positional-arg-name:"template-file" description:"File containing the template to render. Its contents can be also passed through stdin"`
} `positional-args:"yes"`
OutWriter io.Writer
}
// NewRenderTemplateCmd returns a new RenderTemplateCmd
func NewRenderTemplateCmd() *RenderTemplateCmd {
return &RenderTemplateCmd{OutWriter: os.Stdout}
}
func (c *RenderTemplateCmd) getTemplateData() (*templateData, error) {
d := newTemplateData()
if c.DataFile != "" {
if err := d.LoadBatchDataFile(c.DataFile); err != nil {
return nil, fmt.Errorf("cannot read template data file %q: %v", c.DataFile, err)
}
}
return d, nil
}
// Execute performs rendering
func (c *RenderTemplateCmd) Execute(args []string) (err error) {
var in io.Reader
if c.Args.TemplateFile != "" {
fh, err := os.Open(c.Args.TemplateFile)
if err != nil {
return fmt.Errorf("cannot open template file: %v", err)
}
defer fh.Close()
in = fh
} else if hasPipedStdin() {
in = os.Stdin
} else {
return fmt.Errorf("you must provide a template file as an argument or through stdin")
}
data, err := c.getTemplateData()
if err != nil {
return err
}
renderer := newHandlerbarsRenderer()
str, err := renderer.RenderTemplate(in, data)
if err != nil {
return err
}
_, err = fmt.Fprint(c.OutWriter, str)
return err
}
func hasPipedStdin() bool {
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
return true
}
return false
}