Matthew Rich
e695278d0c
All checks were successful
Declarative Tests / test (push) Successful in 48s
84 lines
1.8 KiB
Go
84 lines
1.8 KiB
Go
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
|
|
|
|
package resource
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"gopkg.in/yaml.v3"
|
|
"log/slog"
|
|
)
|
|
|
|
type Declaration struct {
|
|
Type string `yaml:"type"`
|
|
Attributes yaml.Node `yaml:"attributes"`
|
|
Implementation Resource `-`
|
|
}
|
|
|
|
type ResourceLoader interface {
|
|
LoadDecl(string) error
|
|
}
|
|
|
|
type StateTransformer interface {
|
|
Apply() error
|
|
}
|
|
|
|
type YamlLoader func(string, any) error
|
|
|
|
func YamlLoadDecl(yamlFileResourceDeclaration string, resource any) error {
|
|
if err := yaml.Unmarshal([]byte(yamlFileResourceDeclaration), resource); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func NewDeclaration() *Declaration {
|
|
return &Declaration{}
|
|
}
|
|
|
|
func (d *Declaration) LoadDecl(yamlResourceDeclaration string) error {
|
|
return YamlLoadDecl(yamlResourceDeclaration, d)
|
|
}
|
|
|
|
func (d *Declaration) NewResource() error {
|
|
uri := fmt.Sprintf("%s://", d.Type)
|
|
newResource, err := ResourceTypes.New(uri)
|
|
d.Implementation = newResource
|
|
return err
|
|
}
|
|
|
|
func (d *Declaration) LoadResourceFromYaml() (Resource, error) {
|
|
var errResource error
|
|
if d.Implementation == nil {
|
|
errResource = d.NewResource()
|
|
if errResource != nil {
|
|
return nil, errResource
|
|
}
|
|
}
|
|
d.Attributes.Decode(d.Implementation)
|
|
d.Implementation.ResolveId(context.Background())
|
|
return d.Implementation, errResource
|
|
}
|
|
|
|
func (d *Declaration) UpdateYamlFromResource() error {
|
|
if d.Implementation != nil {
|
|
return d.Attributes.Encode(d.Implementation)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (d *Declaration) Resource() Resource {
|
|
return d.Implementation
|
|
}
|
|
|
|
func (d *Declaration) SetURI(uri string) error {
|
|
slog.Info("SetURI()", "uri", uri)
|
|
d.Implementation = NewResource(uri)
|
|
if d.Implementation == nil {
|
|
panic("unknown resource")
|
|
}
|
|
d.Type = d.Implementation.Type()
|
|
d.Implementation.Read(context.Background()) // fix context
|
|
return nil
|
|
}
|