jx/internal/resource/declaration.go
Matthew Rich ce95306eb1
All checks were successful
Declarative Tests / test (push) Successful in 53s
add support for file resource access/mod times
2024-03-24 18:36:21 -07:00

85 lines
1.9 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
//
package resource
import (
"context"
"fmt"
"log/slog"
"gopkg.in/yaml.v3"
)
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
}