summaryrefslogtreecommitdiff
path: root/pkg/variables.go
blob: ed09d31ae76f16f3c31d5178170b9365058ade59 (plain)
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
package gonf

import (
	"fmt"
	"log/slog"
)

// ----- Globals ---------------------------------------------------------------
var variables map[string]*VariablePromise

// ----- Init ------------------------------------------------------------------
func init() {
	variables = make(map[string]*VariablePromise)
}

// ----- Public ----------------------------------------------------------------
func AppendVariable(name string, values ...string) *VariablePromise {
	if v, ok := variables[name]; ok {
		if l, ok := v.value.(*StringsListValue); ok {
			l.Append(values...)
		}
		return v
	}
	v := &VariablePromise{
		isDefault: false,
		name:      name,
		value:     &StringsListValue{values},
	}
	variables[name] = v
	return v
}

func Default(name string, value string) *VariablePromise {
	if v, ok := variables[name]; ok {
		if !v.isDefault {
			slog.Debug("default would overwrite a variable, ignoring", "name", name, "old_value", v.value, "new_value", value)
			return nil
		}
		slog.Error("default is being overwritten", "name", name, "old_value", v.value, "new_value", value)
	}
	v := &VariablePromise{
		isDefault: true,
		name:      name,
		value:     interfaceToTemplateValue(value),
	}
	variables[name] = v
	return v
}

func Variable(name string, value string) *VariablePromise {
	if v, ok := variables[name]; ok && !v.isDefault {
		slog.Error("variable is being overwritten", "name", name, "old_value", v, "new_value", value)
	}
	v := &VariablePromise{
		isDefault: false,
		name:      name,
		value:     interfaceToTemplateValue(value),
	}
	variables[name] = v
	return v
}

type VariablePromise struct {
	isDefault bool
	name      string
	value     Value
}

// We want VariablePromise to satisfy the Value interface
func (s VariablePromise) Bytes() []byte {
	return s.value.Bytes()
}
func (s VariablePromise) String() string {
	return s.value.String()
}

// ----- Internal --------------------------------------------------------------
func getVariable(name string) string {
	if v, ok := variables[name]; ok {
		return v.value.String()
	} else {
		slog.Error("undefined variable or default", "name", name)
		panic(fmt.Sprintf("undefined variable or default %s", name))
	}
}