jx/internal/resource/document.go

101 lines
2.0 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 16:15:27 +00:00
package resource
import (
"encoding/json"
"errors"
2024-03-25 20:31:06 +00:00
_ "fmt"
"github.com/xeipuuv/gojsonschema"
2024-03-25 20:31:06 +00:00
"gopkg.in/yaml.v3"
"io"
_ "log"
_ "net/url"
"strings"
2024-03-20 16:15:27 +00:00
)
type Document struct {
ResourceDecls []Declaration `json:"resources" yaml:"resources"`
2024-03-20 16:15:27 +00:00
}
func NewDocument() *Document {
2024-03-25 20:31:06 +00:00
return &Document{}
2024-03-20 16:15:27 +00:00
}
func (d *Document) Load(r io.Reader) error {
2024-04-05 17:22:17 +00:00
c := NewYAMLDecoder(r)
return c.Decode(d);
}
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())
2024-03-25 20:31:06 +00:00
}
}
return nil
2024-03-20 16:15:27 +00:00
}
2024-03-20 19:23:31 +00:00
func (d *Document) Resources() []Declaration {
2024-03-25 20:31:06 +00:00
return d.ResourceDecls
2024-03-20 16:15:27 +00:00
}
2024-03-20 19:23:31 +00:00
func (d *Document) Apply() error {
2024-03-25 20:31:06 +00:00
for i := range d.ResourceDecls {
if e := d.ResourceDecls[i].Resource().Apply(); e != nil {
return e
}
}
return nil
2024-03-20 19:23:31 +00:00
}
2024-03-25 20:31:06 +00:00
func (d *Document) Generate(w io.Writer) error {
e := NewYAMLEncoder(w)
2024-04-03 19:27:16 +00:00
err := e.Encode(d);
if err == nil {
return e.Close()
}
e.Close()
return err
2024-03-20 19:23:31 +00:00
}
func (d *Document) AddResourceDeclaration(resourceType string, resourceDeclaration Resource) {
2024-03-25 20:31:06 +00:00
decl := NewDeclaration()
decl.Type = TypeName(resourceType)
decl.Attributes = resourceDeclaration
2024-03-25 20:31:06 +00:00
d.ResourceDecls = append(d.ResourceDecls, *decl)
2024-03-20 19:23:31 +00:00
}
func (d *Document) AddResource(uri string) error {
2024-03-25 20:31:06 +00:00
//parsedResourceURI, e := url.Parse(uri)
//if e == nil {
decl := NewDeclaration()
2024-04-03 19:27:16 +00:00
if e := decl.SetURI(uri); e != nil {
return e
}
2024-03-25 20:31:06 +00:00
d.ResourceDecls = append(d.ResourceDecls, *decl)
//}
return nil
2024-03-20 19:23:31 +00:00
}
func (d *Document) JSON() ([]byte, error) {
return json.Marshal(d)
}
func (d *Document) YAML() ([]byte, error) {
return yaml.Marshal(d)
}