Skip to content

Commit

Permalink
Adding support for JSON files as a data source for the template
Browse files Browse the repository at this point in the history
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
  • Loading branch information
hairyhenderson committed May 14, 2016
1 parent 7764fa6 commit cd99095
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
34 changes: 34 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,46 @@
package main

import (
"encoding/json"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
)

// Context for templates
type Context struct {
Data map[string]interface{}
}

func parseFiles(context *Context, files []string) {
for _, file := range files {
ext := filepath.Ext(file)
if ext != ".json" {
log.Fatalf("Only JSON data files are supported right now (%v)", file)
}
name := strings.Split(filepath.Base(file), ext)[0]
log.Printf("Parsing %q", name)
f, err := ioutil.ReadFile(file)
if err != nil {
log.Fatalf("Error while reading %q: %v", file, err)
}
context.Data[name] = parseJSON(f)
}
}

func parseJSON(bytes []byte) interface{} {
var obj interface{}
json.Unmarshal(bytes, &obj)
return obj
}

// NewContext - constructor
func NewContext(files []string) *Context {
context := &Context{make(map[string]interface{})}
parseFiles(context, files)
return context
}

// Env - Map environment variables for use in a template
Expand Down
31 changes: 30 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,29 @@ import (
"text/template"
)

// version
const Version = "0.1.0"

type dataFiles []string

var (
context *Context
dataFilesFlag dataFiles
verFlag *bool
)

func (d *dataFiles) String() string {
return fmt.Sprint(*d)
}

func (d *dataFiles) Set(value string) error {
*d = append(*d, value)
return nil
}

func init() {
ver := flag.Bool("v", false, "Print version and exit")
flag.Var(&dataFilesFlag, "d", "Data file to resolve. Repeat to add more to the context.")
flag.Parse()
if *ver {
fmt.Println(version.Version)
Expand All @@ -34,7 +55,6 @@ type Gomplate struct {

// RunTemplate -
func (g *Gomplate) RunTemplate(in io.Reader, out io.Writer) {
context := &Context{}
text, err := ioutil.ReadAll(in)
if err != nil {
log.Fatalf("Read failed!\n%v\n", err)
Expand Down Expand Up @@ -76,6 +96,15 @@ func NewGomplate() *Gomplate {
}

func main() {
flag.Parse()

if *verFlag {
fmt.Println(Version)
os.Exit(0)
}

context = NewContext(dataFilesFlag)

g := NewGomplate()
g.RunTemplate(os.Stdin, os.Stdout)
}

0 comments on commit cd99095

Please sign in to comment.