about summary refs log tree commit diff
path: root/context/context.go
blob: 2de78541e7e6100f6ff41ef7efb622ce6f78dfb8 (plain) (blame)
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
package context

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"path"
	"strings"

	"github.com/ghodss/yaml"
	"github.com/polydawn/meep"
)

type ResourceSet struct {
	Name   string                 `json:"name"`
	Values map[string]interface{} `json:"values"`

	// Fields for resource set collections
	Include []ResourceSet `json:"include"`
	Parent  *string
}

type Context struct {
	Name         string                 `json:"context"`
	Global       map[string]interface{} `json:"global"`
	ResourceSets []ResourceSet          `json:"include"`
	BaseDir      string
}

type ContextLoadingError struct {
	meep.AllTraits
	Filename string
}

// Attempt to load and deserialise a Context from the specified file.
func LoadContextFromFile(filename string) (*Context, error) {
	file, err := ioutil.ReadFile(filename)

	if err != nil {
		return nil, meep.New(
			&ContextLoadingError{Filename: filename},
			meep.Cause(err),
		)
	}

	var c Context

	if strings.HasSuffix(filename, "json") {
		err = json.Unmarshal(file, &c)
	} else if strings.HasSuffix(filename, "yaml") || strings.HasSuffix(filename, "yml") {
		err = yaml.Unmarshal(file, &c)
	} else {
		return nil, meep.New(
			&ContextLoadingError{Filename: filename},
			meep.Cause(fmt.Errorf("File format not supported. Must be JSON or YAML.")),
		)
	}

	if err != nil {
		return nil, meep.New(
			&ContextLoadingError{Filename: filename},
			meep.Cause(err),
		)
	}

	c.BaseDir = path.Dir(filename)

	return &c, nil
}

// Flattens resource set collections, i.e. resource sets that themselves have an additional 'include' field set.
// Those will be regarded as a short-hand for including multiple resource sets from a subfolder.
// See https://github.com/tazjin/kontemplate/issues/9 for more information.
func flattenResourceSetCollections(rs *[]ResourceSet) *[]ResourceSet {
	flattened := make([]ResourceSet, 0)

	for _, r := range *rs {
		if len(r.Include) == 0 {
			flattened = append(flattened, r)
		} else {
			for _, subResourceSet := range r.Include {
				subResourceSet.Parent = &r.Name
				subResourceSet.Name = path.Join(r.Name, subResourceSet.Name)
				flattened = append(flattened, subResourceSet)
			}
		}
	}

	return &flattened
}