Files
beatglow/config/decode.go
T
2026-10-29 17:28:51 +01:00

189 lines
4.3 KiB
Go

package config
import (
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/BurntSushi/toml"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/json"
"github.com/sirupsen/logrus"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/function"
)
var evalContext = &hcl.EvalContext{
Functions: map[string]function.Function{
"hex": hexFunc,
"bounds": boundsFunc,
"rotary": rotaryFunc,
"volume": volumeFunc,
//"volume": volumeFunc,
//"goto": gotoFunc,
},
}
// Load the configuration file.
func Load(name string) (*Structure, error) {
log := logrus.WithField("path", name)
log.Debug("loading configuration")
source, err := os.ReadFile(name)
if err != nil {
return nil, err
}
var (
config = new(Structure)
ctx *hcl.EvalContext
file *hcl.File
meta toml.MetaData
diag hcl.Diagnostics
)
switch ext := strings.ToLower(filepath.Ext(name)); ext {
case ".json":
log.Trace("parsing as JSON")
file, diag = json.Parse(source, name)
case ".hcl", ".cfg", ".conf":
log.Trace("parsing as HCL")
start := hcl.Pos{Line: 1, Column: 1}
file, diag = hclsyntax.ParseConfig(source, name, start)
case ".toml":
log.Trace("parsing as TOML")
if meta, err = toml.Decode(string(source), config); err != nil {
return nil, err
} else if undecoded := meta.Undecoded(); len(undecoded) > 0 {
diag = diag.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Undecoded contents",
Detail: fmt.Sprintf("Cannot read from %s: undecoded items in configuration: %v.", name, undecoded),
})
return nil, diag
}
default:
diag = diag.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Unsupported file format",
Detail: fmt.Sprintf("Cannot read from %s: unrecognized file format suffix %q.", name, ext),
})
return nil, diag
}
if diag.HasErrors() {
return nil, diag
}
if diag = gohcl.DecodeBody(file.Body, ctx, config); diag.HasErrors() {
return nil, diag
}
return config, nil
}
func ExplainError(name string, err error) bool {
fmt.Printf("error type %T\n", err)
if diags, ok := err.(hcl.Diagnostics); ok {
for _, diag := range diags {
if diag.Subject != nil {
return explainSubject(diag)
}
}
}
return false
}
func explainSubject(diag *hcl.Diagnostic) bool {
if diag.Subject == nil || diag.Subject.Filename == "" {
return false
}
source, err := os.ReadFile(diag.Subject.Filename)
if err != nil {
return false
}
fmt.Printf("Fatal error parsing %s:\n", diag.Subject)
lines := strings.Split(string(source), "\n")
start := diag.Subject.Start.Line - 3
if start < 0 {
start = 0
}
for line := start; line < diag.Subject.Start.Line; line++ {
fmt.Printf("%4d| %s\n", line+1, lines[line])
}
fmt.Print(" ...|")
if diag.Subject.Start.Column > 1 {
fmt.Print(strings.Repeat(" ", diag.Subject.Start.Column))
}
fmt.Print("^- ")
fmt.Println(diag.Summary + "\n")
fmt.Println(diag.Detail)
return true
}
var (
hexFunc = function.New(&function.Spec{
Params: []function.Parameter{{
Name: "number",
Type: cty.String,
}},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
v := args[0].AsString()
if strings.HasPrefix(strings.ToLower(v), "0x") {
v = v[2:]
}
i, err := strconv.ParseUint(v, 16, 64)
if err != nil {
return cty.NumberUIntVal(0), err
}
return cty.NumberUIntVal(i), nil
},
})
rotaryFunc = function.New(&function.Spec{
Params: []function.Parameter{{
Name: "action",
Type: cty.String,
}},
Type: function.StaticReturnType(cty.String),
})
boundsFunc = function.New(&function.Spec{
Params: []function.Parameter{{
Name: "width",
Type: cty.Number,
}, {
Name: "height",
Type: cty.Number,
}},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
w := args[0].AsString()
h := args[1].AsString()
return cty.StringVal(w + "x" + h), nil
},
})
volumeFunc = function.New(&function.Spec{
Params: []function.Parameter{{
Name: "level",
Type: cty.Number,
}},
Type: function.StaticReturnType(cty.String),
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
return cty.StringVal("volume:" + args[0].AsString()), nil
},
})
)