Add 'template_directory' setting
authorMikael Berthe <mikael@lilotux.net>
Sun, 07 May 2017 11:56:37 +0200
changeset 82 9ac2281c07d7
parent 81 b1671f83e91b
child 83 57afac822019
Add 'template_directory' setting If set, template files are looked up relatively from this repository first (unless they are absolute paths or start with "./" or "../").
cmd/utils.go
templates/README.md
--- a/cmd/utils.go	Sun May 07 11:46:28 2017 +0200
+++ b/cmd/utils.go	Sun May 07 11:56:37 2017 +0200
@@ -9,6 +9,8 @@
 	"fmt"
 	"io/ioutil"
 	"os"
+	"path/filepath"
+	"strings"
 
 	"github.com/pkg/errors"
 	"github.com/spf13/cobra"
@@ -57,7 +59,7 @@
 	if of == "template" {
 		opt = outputTemplate
 		if outputTemplateFile != "" {
-			tmpl, err := ioutil.ReadFile(outputTemplateFile)
+			tmpl, err := readTemplate(outputTemplateFile, viper.GetString("template_directory"))
 			if err != nil {
 				return nil, err
 			}
@@ -67,6 +69,30 @@
 	return printer.NewPrinter(of, opt)
 }
 
+func readTemplate(name, templateDir string) ([]byte, error) {
+	if strings.HasPrefix(name, "/") || strings.HasPrefix(name, "./") || strings.HasPrefix(name, "../") {
+		return ioutil.ReadFile(name)
+	}
+
+	if templateDir != "" {
+		// If the template file can be found in the template directory,
+		// use this file.
+		fullName := filepath.Join(templateDir, name)
+		if fileExists(fullName) {
+			name = fullName
+		}
+	}
+
+	return ioutil.ReadFile(name)
+}
+
+func fileExists(filename string) bool {
+	if _, err := os.Stat(filename); err != nil {
+		return false
+	}
+	return true
+}
+
 func errPrint(format string, a ...interface{}) (n int, err error) {
 	return fmt.Fprintf(os.Stderr, format+"\n", a...)
 }
--- a/templates/README.md	Sun May 07 11:46:28 2017 +0200
+++ b/templates/README.md	Sun May 07 11:56:37 2017 +0200
@@ -8,4 +8,9 @@
 
     madonctl timeline --limit 2 --template-file ansi-status.tmpl
 
-Feel free to contribute if you have nice templates of if you want to work on themes as well!
+The template prefix directory can be set in the configuration file with the 'template_directory' setting,
+or with the `MADONCTL_TEMPLATE_DIRECTORY` environment variable. \
+If set, template files are looked up relatively from this repository first
+(unless they are absolute paths or start with "./" or "../").
+
+Feel free to contribute if you have nice templates or if you want to work on themes as well!