jx/internal/resource/document.go

97 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-03-25 20:31:06 +00:00
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())
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)
e.Encode(d)
return e.Close()
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()
decl.SetURI(uri)
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)
}