-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
98 lines (89 loc) · 2.33 KB
/
main.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
package main
import (
"flag"
"fmt"
"html/template"
"io"
"io/ioutil"
"os"
ttemplate "text/template"
"github.com/Masterminds/sprig/v3"
)
func main() {
f := flag.CommandLine
f.Usage = func() {
fmt.Fprintf(f.Output(), "A command applying Go template leveraging the Sprig package\n\n"+
"Usage:\n sprig [-format <format>] [-file <templateFile>] <input>\n\nOptions:\n")
f.PrintDefaults()
fmt.Fprintln(f.Output(), "\nExamples:\n"+
" echo \"ts {{div now.UnixNano 1e6}}# Hi random Gopher {{uuidv4}} 👋.\" | sprig\n\n"+
"See https://masterminds.github.io/sprig/ for more information about the available template functions")
}
format := f.String("format", "text", "The template format (text|html) to use.")
tmplFile := f.String("file", "", "A go template file to use as an alternative to stdin.")
f.Parse(os.Args[1:])
var tmpl io.Reader = os.Stdin
if isFlagUsed(f, "file") {
file, err := os.Open(*tmplFile)
if err != nil {
parseFail(f, "%s", err)
}
defer file.Close()
tmpl = file
}
if len(f.Args()) > 1 {
parseFail(f, "expects only one <input> argument")
}
if err := run(*format, flag.Arg(0), tmpl, os.Stdout); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(2)
}
}
func parseFail(f *flag.FlagSet, format string, args ...interface{}) {
fmt.Fprintf(f.Output(), format+"\n", args...)
f.Usage()
os.Exit(2)
}
func isFlagUsed(f *flag.FlagSet, name string) bool {
found := false
f.Visit(func(f *flag.Flag) {
if f.Name == name {
found = true
}
})
return found
}
func run(format, input string, tmpl io.Reader, output io.Writer) error {
templateError := func(err error) error {
return fmt.Errorf("could not apply the go template (%s): %w", format, err)
}
b, err := ioutil.ReadAll(tmpl)
if err != nil {
return templateError(err)
}
switch format {
case "text":
fMap := sprig.TxtFuncMap()
t, err := ttemplate.New("tmpl").Funcs(fMap).Parse(string(b))
if err != nil {
return templateError(err)
}
err = t.Execute(output, input)
if err != nil {
return templateError(err)
}
case "html":
fMap := sprig.HtmlFuncMap()
t, err := template.New("tmpl").Funcs(fMap).Parse(string(b))
if err != nil {
return templateError(err)
}
err = t.Execute(output, input)
if err != nil {
return templateError(err)
}
default:
return fmt.Errorf("invalid %s format", format)
}
return nil
}