diff options
Diffstat (limited to 'pkg/variables.go')
-rw-r--r-- | pkg/variables.go | 85 |
1 files changed, 85 insertions, 0 deletions
diff --git a/pkg/variables.go b/pkg/variables.go new file mode 100644 index 0000000..ed09d31 --- /dev/null +++ b/pkg/variables.go @@ -0,0 +1,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)) + } +} |