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
|
package main
import (
"encoding/json"
"flag"
"fmt"
"log"
"os"
"strings"
)
var (
conf_f = flag.String("c", "", "Path to the configuration file.")
template_dir_f = flag.String("d", ".", "Template directory.")
template_f = flag.String("f", "", "Templates to render, a comma separated list.")
ext_f = flag.String("e", ".tmpl", "Extension of template files")
is_html_f = flag.Bool("html", false, "Enable HTML context sensitivy.")
)
func main() {
flag.Parse()
if *template_f == "" {
fmt.Println("Please provide a template to render with the -f option.")
os.Exit(1)
}
// Reading config from environment if not set (case insensitive)
*conf_f = GetVarFromEnv(*conf_f, "config")
*template_dir_f = GetVarFromEnv(*template_dir_f, "template_directory")
*template_f = GetVarFromEnv(*template_f, "templates")
// Read configuration file with the template data
data := NewConfiguration(*conf_f)
// Splits the templates
var templates []string
if strings.Contains(*template_f, ",") {
templates = strings.Split(*template_f, ",")
} else {
templates = strings.Split(*template_f, " ")
}
// Clean out the filenames if they start with the template dirname (shell globbing)
for index, template := range templates {
if strings.HasPrefix(template, *template_dir_f+"/") {
templates[index] = strings.TrimPrefix(template, *template_dir_f+"/")
} else {
templates[index] = strings.TrimPrefix(template, *template_dir_f)
}
}
// Enable HTML context sensitivy on demand
if *is_html_f {
ParseHTML(templates, data)
} else {
ParseText(templates, data)
}
}
func NewConfiguration(path string) interface{} {
if path == "" {
return nil
}
file, err := os.Open(path)
if err != nil {
log.Print("INFO: Error opening config file. Is it a valid file?")
return nil
}
fi, err := file.Stat()
if err != nil {
log.Fatal(err)
}
data := make([]byte, int64(fi.Size()))
file.Read(data)
var json_data interface{}
json.Unmarshal(data, &json_data)
return json_data
}
func GetVarFromEnv(s, key string) string {
if s == "" {
s = os.Getenv(key)
}
if s == "" {
s = os.Getenv(strings.ToUpper(key))
}
return s
}
|