-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathepp.go
100 lines (78 loc) · 1.85 KB
/
epp.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
95
96
97
98
99
100
package main
import (
"encoding/base64"
"flag"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/flosch/pongo2"
)
var (
// Version of the application
Version string
// GitCommit of the application
GitCommit string
output = flag.String("o", "", "output file")
version = flag.Bool("version", false, "print epp version")
)
func init() {
pongo2.RegisterFilter("b64enc", filterBase64Encode)
}
func main() {
flag.Parse()
if *version {
fmt.Fprintf(os.Stderr, "epp %s (%s)\n", Version, GitCommit)
os.Exit(0)
}
if len(flag.Args()) == 0 {
fmt.Fprintln(os.Stderr, "error: an input file is required")
os.Exit(1)
}
fileContents, err := readInput(flag.Arg(0))
if err != nil {
fmt.Fprintf(os.Stderr, "IO error: %s\n", err)
os.Exit(1)
}
out, err := Parse(fileContents)
if err != nil {
fmt.Fprintf(os.Stderr, "templating error: %s\n", err)
os.Exit(1)
}
if *output == "" {
fmt.Printf(string(out))
return
}
err = ioutil.WriteFile(*output, out, 0644)
if err != nil {
fmt.Fprintf(os.Stderr, "IO error: %s\n", err)
os.Exit(1)
}
}
// Parse parses the input and returns the output
func Parse(input []byte) ([]byte, error) {
tpl, err := pongo2.FromString(string(input))
if err != nil {
return nil, err
}
context := environToContext()
return tpl.ExecuteBytes(context)
}
func readInput(input string) ([]byte, error) {
if inputFile := flag.Arg(0); inputFile == "-" {
return ioutil.ReadAll(os.Stdin)
}
return ioutil.ReadFile(input)
}
func environToContext() pongo2.Context {
ctx := pongo2.Context{}
for _, env := range os.Environ() {
variable := strings.SplitN(env, "=", 2)
key, value := variable[0], variable[1]
ctx[key] = value
}
return ctx
}
func filterBase64Encode(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
return pongo2.AsValue(base64.StdEncoding.EncodeToString([]byte(in.String()))), nil
}