forked from osteele/liquid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
79 lines (72 loc) · 1.4 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
// Package main defines a command-line interface to the Liquid engine.
//
// This command intended for testing and bug reports.
//
// Examples:
//
// echo '{{ "Hello " | append: "World" }}' | liquid
// liquid source.tpl
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"github.com/osteele/liquid"
)
// for testing
var (
stderr = os.Stderr
stdout io.Writer = os.Stdout
stdin io.Reader = os.Stdin
exit = os.Exit
)
func main() {
if err := run(os.Args[1:]); err != nil {
fmt.Fprintln(stderr, err) // nolint: gas
os.Exit(1)
}
}
func run(args []string) error {
switch {
case len(args) == 0:
buf := new(bytes.Buffer)
if _, err := io.Copy(buf, stdin); err != nil {
return err
}
return render(buf.Bytes(), "")
case args[0] == "-h" || args[0] == "--help":
usage()
case strings.HasPrefix(args[0], "-"):
// undefined flag
usage()
exit(1)
case len(args) == 1:
s, err := ioutil.ReadFile(args[0])
if err != nil {
return err
}
return render(s, args[0])
default:
usage()
exit(1)
}
return nil
}
func render(b []byte, filename string) (err error) {
tpl, err := liquid.NewEngine().ParseTemplate(b)
if err != nil {
return err
}
out, err := tpl.Render(map[string]interface{}{})
if err != nil {
return err
}
_, err = stdout.Write(out)
return err
}
func usage() {
fmt.Fprintf(stdout, "usage: %s [FILE]\n", os.Args[0]) // nolint: gas
}