jx/internal/resource/declaration.go

84 lines
1.8 KiB
Go
Raw Normal View History

2024-03-20 19:23:31 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
2024-03-22 17:39:06 +00:00
2024-03-20 19:23:31 +00:00
package resource
import (
2024-03-25 20:31:06 +00:00
"context"
"fmt"
"gopkg.in/yaml.v3"
"log/slog"
2024-03-20 19:23:31 +00:00
)
type Declaration struct {
2024-03-25 20:31:06 +00:00
Type string `yaml:"type"`
Attributes yaml.Node `yaml:"attributes"`
Implementation Resource `-`
2024-03-20 19:23:31 +00:00
}
type ResourceLoader interface {
2024-03-25 20:31:06 +00:00
LoadDecl(string) error
2024-03-20 19:23:31 +00:00
}
type StateTransformer interface {
2024-03-25 20:31:06 +00:00
Apply() error
2024-03-20 19:23:31 +00:00
}
type YamlLoader func(string, any) error
func YamlLoadDecl(yamlFileResourceDeclaration string, resource any) error {
2024-03-25 20:31:06 +00:00
if err := yaml.Unmarshal([]byte(yamlFileResourceDeclaration), resource); err != nil {
return err
}
return nil
2024-03-20 19:23:31 +00:00
}
func NewDeclaration() *Declaration {
2024-03-25 20:31:06 +00:00
return &Declaration{}
2024-03-20 19:23:31 +00:00
}
func (d *Declaration) LoadDecl(yamlResourceDeclaration string) error {
2024-03-25 20:31:06 +00:00
return YamlLoadDecl(yamlResourceDeclaration, d)
2024-03-20 19:23:31 +00:00
}
func (d *Declaration) NewResource() error {
2024-03-25 20:31:06 +00:00
uri := fmt.Sprintf("%s://", d.Type)
newResource, err := ResourceTypes.New(uri)
d.Implementation = newResource
return err
2024-03-20 19:23:31 +00:00
}
func (d *Declaration) LoadResourceFromYaml() (Resource, error) {
2024-03-25 20:31:06 +00:00
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
2024-03-20 19:23:31 +00:00
}
func (d *Declaration) UpdateYamlFromResource() error {
2024-03-25 20:31:06 +00:00
if d.Implementation != nil {
return d.Attributes.Encode(d.Implementation)
}
return nil
2024-03-20 19:23:31 +00:00
}
func (d *Declaration) Resource() Resource {
2024-03-25 20:31:06 +00:00
return d.Implementation
2024-03-20 19:23:31 +00:00
}
func (d *Declaration) SetURI(uri string) error {
2024-03-25 20:31:06 +00:00
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
2024-03-20 19:23:31 +00:00
}