-
Notifications
You must be signed in to change notification settings - Fork 0
/
endpoint_tree.go
118 lines (96 loc) · 2.47 KB
/
endpoint_tree.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"fmt"
"strings"
"github.com/fgrosse/gotility"
)
type endpointTree struct {
endpoints []endpoint
nodes map[string]*endpointNode
rootNodes gotility.StringSet
}
type endpointNode struct {
*endpoint
children []*endpointNode
}
func newEndpointTree(endpoints []endpoint) endpointTree {
t := endpointTree{
endpoints: endpoints,
nodes: map[string]*endpointNode{},
rootNodes: gotility.StringSet{},
}
for i := range endpoints {
n := endpoints[i].Name
t.nodes[n] = &endpointNode{&endpoints[i], []*endpointNode{}}
t.rootNodes.Set(n)
}
return t
}
func (t endpointTree) process() error {
// build up the inheritance tree
for name, o := range t.nodes {
if o.Extends == "" {
continue
}
parent, ok := t.nodes[o.Extends]
if !ok {
return fmt.Errorf("endpoint %q extends an unknown endpoint %q", name, o.Extends)
}
parent.children = append(parent.children, t.nodes[name])
t.rootNodes.Delete(name)
}
// check for any inheritance cycles
for i := range t.endpoints {
name := t.endpoints[i].Name
trace := gotility.StringSlice{name}
if err := t.checkForCycles(t.nodes[name], trace); err != nil {
return err
}
}
// finally inherit attributes in the tree
for name := range t.rootNodes {
for _, child := range t.nodes[name].children {
t.inheritAttributes(t.nodes[name], child)
}
}
return nil
}
func (t endpointTree) checkForCycles(node *endpointNode, trace gotility.StringSlice) error {
for _, child := range node.children {
if trace.Contains(child.Name) {
trace.Add(child.Name)
trace.Reverse()
return fmt.Errorf("Detected inheritance cycle: %s", strings.Join(trace, " -> "))
}
trace.Add(child.Name)
if err := t.checkForCycles(child, trace); err != nil {
return err
}
trace.DeleteByValue(child.Name)
}
return nil
}
func (t endpointTree) inheritAttributes(parent, child *endpointNode) {
if parent.Method != "" && child.Method == "" {
child.Method = parent.Method
}
if parent.URI != "" && child.URI == "" {
child.URI = parent.URI
}
for _, parentParameter := range parent.Parameters {
keyExists := false
for _, existingParameter := range child.Parameters {
if existingParameter.Name == parentParameter.Name {
keyExists = true
}
}
if keyExists {
// don't overwrite parameters that already exist in the children
continue
}
child.Parameters = append(child.Parameters, parentParameter)
}
for _, grandChild := range child.children {
t.inheritAttributes(child, grandChild)
}
}