forked from tliron/puccini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclout.go
84 lines (70 loc) · 1.85 KB
/
clout.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package clout
import (
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/tliron/kutil/ard"
"github.com/tliron/kutil/format"
)
const Version = "1.0"
//
// Clout
//
type Clout struct {
Version string `json:"version" yaml:"version"`
Metadata ard.StringMap `json:"metadata" yaml:"metadata"`
Properties ard.StringMap `json:"properties" yaml:"properties" `
Vertexes Vertexes `json:"vertexes" yaml:"vertexes"`
}
func NewClout() *Clout {
return &Clout{
Version: Version,
Metadata: make(ard.StringMap),
Properties: make(ard.StringMap),
Vertexes: make(Vertexes),
}
}
type MarshalableCloutStringMaps Clout
func (self *Clout) MarshalableStringMaps() any {
return &MarshalableCloutStringMaps{
Version: self.Version,
Metadata: ard.EnsureStringMaps(self.Metadata),
Properties: ard.EnsureStringMaps(self.Properties),
Vertexes: self.Vertexes,
}
}
// json.Marshaler interface
func (self *Clout) MarshalJSON() ([]byte, error) {
// JavaScript requires keys to be strings, so we would lose complex keys
return json.Marshal(self.MarshalableStringMaps())
}
func (self *Clout) Resolve() error {
if self.Version == "" {
return errors.New("no Clout \"Version\"")
}
if self.Version != Version {
return fmt.Errorf("unsupported Clout version: %q", self.Version)
}
for key, v := range self.Vertexes {
v.Clout = self
v.ID = key
for _, e := range v.EdgesOut {
var ok bool
if e.Target, ok = self.Vertexes[e.TargetID]; !ok {
return fmt.Errorf("could not resolve Clout, bad TargetID: %q", e.TargetID)
}
e.Source = v
e.Target.EdgesIn = append(e.Target.EdgesIn, e)
}
}
return nil
}
func (self *Clout) Normalize() (*Clout, error) {
// TODO: not very efficient
if code, err := format.EncodeYAML(self, " ", false); err == nil {
return Read(strings.NewReader(code), "yaml")
} else {
return nil, err
}
}