From 560becfd32dd7355547938f3c6229060dd395aab Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Thu, 7 Mar 2024 00:54:35 +0100 Subject: chore(repo): renamed gonf subfolder to something more traditional in go land --- pkg/variables.go | 85 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 pkg/variables.go (limited to 'pkg/variables.go') 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)) + } +} -- cgit v1.2.3