Fin/config.go
2025-03-02 05:58:12 -06:00

297 lines
5.8 KiB
Go

package config
import (
"fmt"
"io"
"strconv"
)
// Config holds a single hierarchical structure like JSON
type Config struct {
data map[string]any
}
// NewConfig creates a new empty config
func NewConfig() *Config {
return &Config{
data: make(map[string]any),
}
}
// Get retrieves a value from the config using dot notation
func (c *Config) Get(key string) (any, error) {
if key == "" {
return c.data, nil
}
// Parse the dot-notation path manually
var start, i int
var current any = c.data
for i = 0; i < len(key); i++ {
if key[i] == '.' || i == len(key)-1 {
end := i
if i == len(key)-1 && key[i] != '.' {
end = i + 1
}
part := key[start:end]
// Handle current node based on its type
switch node := current.(type) {
case map[string]any:
// Simple map lookup
val, ok := node[part]
if !ok {
return nil, fmt.Errorf("key %s not found", part)
}
current = val
case []any:
// Must be numeric index
index, err := strconv.Atoi(part)
if err != nil {
return nil, fmt.Errorf("invalid array index: %s", part)
}
if index < 0 || index >= len(node) {
return nil, fmt.Errorf("array index out of bounds: %d", index)
}
current = node[index]
default:
return nil, fmt.Errorf("cannot access %s in non-container value", part)
}
// If we've processed the entire key, return the current value
if i == len(key)-1 || (i < len(key)-1 && key[i] == '.' && end == i) {
if i == len(key)-1 {
return current, nil
}
}
start = i + 1
}
}
return current, nil
}
// GetOr retrieves a value or returns a default if not found
func (c *Config) GetOr(key string, defaultValue any) any {
val, err := c.Get(key)
if err != nil {
return defaultValue
}
return val
}
// GetString gets a value as string
func (c *Config) GetString(key string) (string, error) {
val, err := c.Get(key)
if err != nil {
return "", err
}
switch v := val.(type) {
case string:
return v, nil
case bool:
return strconv.FormatBool(v), nil
case int64:
return strconv.FormatInt(v, 10), nil
case float64:
return strconv.FormatFloat(v, 'f', -1, 64), nil
default:
return "", fmt.Errorf("value for key %s cannot be converted to string", key)
}
}
// GetBool gets a value as boolean
func (c *Config) GetBool(key string) (bool, error) {
val, err := c.Get(key)
if err != nil {
return false, err
}
switch v := val.(type) {
case bool:
return v, nil
case string:
return strconv.ParseBool(v)
default:
return false, fmt.Errorf("value for key %s cannot be converted to bool", key)
}
}
// GetInt gets a value as int64
func (c *Config) GetInt(key string) (int64, error) {
val, err := c.Get(key)
if err != nil {
return 0, err
}
switch v := val.(type) {
case int64:
return v, nil
case float64:
return int64(v), nil
case string:
return strconv.ParseInt(v, 10, 64)
default:
return 0, fmt.Errorf("value for key %s cannot be converted to int", key)
}
}
// GetFloat gets a value as float64
func (c *Config) GetFloat(key string) (float64, error) {
val, err := c.Get(key)
if err != nil {
return 0, err
}
switch v := val.(type) {
case float64:
return v, nil
case int64:
return float64(v), nil
case string:
return strconv.ParseFloat(v, 64)
default:
return 0, fmt.Errorf("value for key %s cannot be converted to float", key)
}
}
// GetArray gets a value as []any
func (c *Config) GetArray(key string) ([]any, error) {
val, err := c.Get(key)
if err != nil {
return nil, err
}
if arr, ok := val.([]any); ok {
return arr, nil
}
return nil, fmt.Errorf("value for key %s is not an array", key)
}
// GetMap gets a value as map[string]any
func (c *Config) GetMap(key string) (map[string]any, error) {
val, err := c.Get(key)
if err != nil {
return nil, err
}
if m, ok := val.(map[string]any); ok {
return m, nil
}
return nil, fmt.Errorf("value for key %s is not a map", key)
}
// Load parses a config from a reader
func Load(r io.Reader) (*Config, error) {
scanner := NewScanner(r)
config := NewConfig()
for {
err := scanner.SkipWhitespace()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
b, err := scanner.PeekByte()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
// Handle comments
if b == '-' {
peekBytes, err := scanner.PeekBytes(2)
if err == nil && len(peekBytes) == 2 && peekBytes[1] == '-' {
err = scanner.scanComment()
if err != nil {
return nil, err
}
continue
}
}
// Process key-value pair
if isLetter(b) {
// Read name
nameToken, err := scanner.scanName(scanner.line, scanner.col)
if err != nil {
return nil, err
}
name := string(nameToken.Value)
// Skip whitespace
err = scanner.SkipWhitespace()
if err != nil {
return nil, err
}
// Must be followed by = or {
b, err = scanner.PeekByte()
if err != nil {
return nil, err
}
if b != '=' && b != '{' {
return nil, scanner.Error("expected '=' or '{' after name")
}
var value any
if b == '=' {
_, _ = scanner.ReadByte() // consume =
err = scanner.SkipWhitespace()
if err != nil {
return nil, err
}
value, err = scanner.ScanValue()
if err != nil {
return nil, err
}
} else { // b == '{'
_, _ = scanner.ReadByte() // consume {
value, err = scanner.scanObjectOrArray()
if err != nil {
return nil, err
}
}
// Store in config
config.data[name] = value
} else {
return nil, scanner.Error("expected name at top level")
}
}
return config, nil
}
// Helpers
func isLetter(b byte) bool {
return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')
}
func isDigit(b byte) bool {
return b >= '0' && b <= '9'
}
func hasDot(s string) bool {
for i := 0; i < len(s); i++ {
if s[i] == '.' {
return true
}
}
return false
}