jx/internal/resource/document.go
Matthew Rich 33dd463180
Some checks failed
Lint / golangci-lint (push) Failing after 9m53s
Declarative Tests / test (push) Failing after 58s
update resource schemas
2024-04-09 12:30:05 -07:00

97 lines
1.9 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource
import (
"encoding/json"
_ "fmt"
"gopkg.in/yaml.v3"
"io"
"log/slog"
_ "net/url"
)
type Document struct {
ResourceDecls []Declaration `json:"resources" yaml:"resources"`
}
func NewDocument() *Document {
return &Document{}
}
func (d *Document) Load(r io.Reader) error {
c := NewYAMLDecoder(r)
return c.Decode(d);
}
func (d *Document) Validate() error {
jsonDocument, jsonErr := d.JSON()
slog.Info("document.Validate() json", "json", jsonDocument, "err", jsonErr)
if jsonErr == nil {
s := NewSchema("document")
err := s.Validate(string(jsonDocument))
if err != nil {
return err
}
/*
for i := range d.ResourceDecls {
if e := d.ResourceDecls[i].Resource().Validate(); e != nil {
return fmt.Errorf("failed to validate resource %s; %w", d.ResourceDecls[i].Resource().URI(), e)
}
}
*/
}
return nil
}
func (d *Document) Resources() []Declaration {
return d.ResourceDecls
}
func (d *Document) Apply() error {
for i := range d.ResourceDecls {
if e := d.ResourceDecls[i].Resource().Apply(); e != nil {
return e
}
}
return nil
}
func (d *Document) Generate(w io.Writer) error {
e := NewYAMLEncoder(w)
err := e.Encode(d);
if err == nil {
return e.Close()
}
e.Close()
return err
}
func (d *Document) AddResourceDeclaration(resourceType string, resourceDeclaration Resource) {
decl := NewDeclaration()
decl.Type = TypeName(resourceType)
decl.Attributes = resourceDeclaration
d.ResourceDecls = append(d.ResourceDecls, *decl)
}
func (d *Document) AddResource(uri string) error {
//parsedResourceURI, e := url.Parse(uri)
//if e == nil {
decl := NewDeclaration()
if e := decl.SetURI(uri); e != nil {
return e
}
d.ResourceDecls = append(d.ResourceDecls, *decl)
//}
return nil
}
func (d *Document) JSON() ([]byte, error) {
return json.Marshal(d)
}
func (d *Document) YAML() ([]byte, error) {
return yaml.Marshal(d)
}