// Copyright 2024 Matthew Rich . All rights reserved. package resource import ( "encoding/json" "errors" _ "fmt" "github.com/xeipuuv/gojsonschema" "gopkg.in/yaml.v3" "io" _ "log" _ "net/url" "strings" ) type Document struct { ResourceDecls []Declaration `json:"resources" yaml:"resources"` } func NewDocument() *Document { return &Document{} } func (d *Document) Load(r io.Reader) error { yamlDecoder := yaml.NewDecoder(r) if e := yamlDecoder.Decode(d); e != nil { return e } return nil } func (d *Document) Validate() error { jsonDocument, jsonErr := d.JSON() if jsonErr == nil { schemaLoader := gojsonschema.NewReferenceLoader("file://schemas/document.jsonschema") documentLoader := gojsonschema.NewBytesLoader(jsonDocument) result, err := gojsonschema.Validate(schemaLoader, documentLoader) if err != nil { return err } if !result.Valid() { schemaErrors := strings.Builder{} for _, err := range result.Errors() { schemaErrors.WriteString(err.String() + "\n") } return errors.New(schemaErrors.String()) } } 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) }