-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmd_fill.go
94 lines (84 loc) · 1.65 KB
/
cmd_fill.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"errors"
"fmt"
"io/ioutil"
"os"
"text/template"
"github.com/urfave/cli"
)
func fillCommand(kmsFlags []cli.Flag) cli.Command {
return cli.Command{
Name: "fill",
Usage: "Fill template by files",
Flags: append([]cli.Flag{
cli.StringFlag{
Name: "template",
Usage: "File path of template file.",
Required: true,
},
cli.StringFlag{
Name: "output",
Usage: "File path of output.",
},
}, kmsFlags...),
Before: initializeKMS,
Action: fillAction,
}
}
func fillAction(c *cli.Context) error {
raw := make(map[string][]byte)
for _, filename := range c.Args() {
// Skip dir
fstat, err := os.Stat(filename)
if err != nil {
return err
}
if fstat.IsDir() {
continue
}
plainText, err := getPlainText(filename)
if errors.Is(err, ErrorInvalidFormat) {
plainText, err = ioutil.ReadFile(filename)
if err != nil {
return err
}
} else if err != nil {
return err
}
raw[filename] = plainText
}
if len(raw) == 0 {
return fmt.Errorf("specify at least one file")
}
result, err := convertToTemplateData(raw)
if err != nil {
return err
}
output := os.Stdout
if outputFile := c.String("output"); outputFile != "" {
err := checkOverwrite(outputFile)
if err != nil {
return err
}
fp, err := os.Create(outputFile)
if err != nil {
return err
}
defer fp.Close()
output = fp
}
tmplString, err := ioutil.ReadFile(c.String("template"))
if err != nil {
return err
}
tmpl, err := template.New("vault-template").Parse(string(tmplString))
if err != nil {
return err
}
err = tmpl.Execute(output, result)
if err != nil {
return err
}
return nil
}