jx/internal/config/generic.go

87 lines
1.7 KiB
Go
Raw Permalink Normal View History

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package config
import (
"context"
"encoding/json"
"net/url"
"fmt"
"decl/internal/data"
"decl/internal/folio"
2024-09-27 00:20:51 +00:00
"decl/internal/codec"
"io"
)
func init() {
folio.DocumentRegistry.ConfigurationTypes.Register([]string{"generic"}, func(u *url.URL) data.Configuration {
2024-07-17 08:34:57 +00:00
g := NewGeneric[any]()
return g
})
}
2024-07-17 08:34:57 +00:00
type Generic[Value any] map[string]Value
2024-07-17 08:34:57 +00:00
func NewGeneric[Value any]() *Generic[Value] {
g := make(Generic[Value])
return &g
}
func (g *Generic[Value]) URI() string {
return fmt.Sprintf("%s://%s", g.Type(), "")
}
func (g *Generic[Value]) SetURI(uri string) error {
return nil
}
func (g *Generic[Value]) SetParsedURI(uri data.URIParser) error {
return nil
}
2024-09-27 00:20:51 +00:00
func (g *Generic[Value]) Load(r io.Reader) (err error) {
err = codec.NewYAMLDecoder(r).Decode(g)
if err == nil {
_, err = g.Read(context.Background())
}
return err
}
func (g *Generic[Value]) LoadYAML(yamlData string) (err error) {
err = codec.NewYAMLStringDecoder(yamlData).Decode(g)
if err == nil {
_, err = g.Read(context.Background())
}
return err
}
func (g *Generic[Value]) Clone() data.Configuration {
jsonGeneric, _ := json.Marshal(g)
2024-07-17 08:34:57 +00:00
clone := NewGeneric[Value]()
if unmarshalErr := json.Unmarshal(jsonGeneric, clone); unmarshalErr != nil {
panic(unmarshalErr)
}
2024-07-17 08:34:57 +00:00
return clone
}
2024-07-17 08:34:57 +00:00
func (g *Generic[Value]) Type() string {
return "generic"
}
2024-07-17 08:34:57 +00:00
func (g *Generic[Value]) Read(context.Context) ([]byte, error) {
return nil, nil
}
2024-07-17 08:34:57 +00:00
func (g *Generic[Value]) GetValue(name string) (result any, err error) {
var ok bool
if result, ok = (*g)[name]; !ok {
err = data.ErrUnknownConfigurationKey
}
return
}
func (g *Generic[Value]) Has(key string) (ok bool) {
_, ok = (*g)[key]
return
}