diff options
Diffstat (limited to 'main.go')
| -rw-r--r-- | main.go | 93 |
1 files changed, 93 insertions, 0 deletions
@@ -0,0 +1,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 +} |
