forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinput.go
92 lines (77 loc) · 2.05 KB
/
input.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
// Copyright 2016 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package topdown
import (
"fmt"
"github.com/open-policy-agent/opa/ast"
)
var errConflictingDoc = fmt.Errorf("conflicting documents")
var errBadPath = fmt.Errorf("bad document path")
func mergeTermWithValues(exist *ast.Term, pairs [][2]*ast.Term) (*ast.Term, error) {
var result *ast.Term
var init bool
for i, pair := range pairs {
if err := ast.IsValidImportPath(pair[0].Value); err != nil {
return nil, errBadPath
}
target := pair[0].Value.(ast.Ref)
// Copy the value if subsequent pairs in the slice would modify it.
for j := i + 1; j < len(pairs); j++ {
other := pairs[j][0].Value.(ast.Ref)
if len(other) > len(target) && other.HasPrefix(target) {
pair[1] = pair[1].Copy()
break
}
}
if len(target) == 1 {
result = pair[1]
init = true
} else {
if !init {
result = exist.Copy()
init = true
}
if result == nil {
result = ast.NewTerm(makeTree(target[1:], pair[1]))
} else {
node := result
done := false
for i := 1; i < len(target)-1 && !done; i++ {
if child := node.Get(target[i]); child == nil {
obj, ok := node.Value.(ast.Object)
if !ok {
return nil, errConflictingDoc
}
obj.Insert(target[i], ast.NewTerm(makeTree(target[i+1:], pair[1])))
done = true
} else {
node = child
}
}
if !done {
obj, ok := node.Value.(ast.Object)
if !ok {
return nil, errConflictingDoc
}
obj.Insert(target[len(target)-1], pair[1])
}
}
}
}
if !init {
result = exist
}
return result, nil
}
// makeTree returns an object that represents a document where the value v is
// the leaf and elements in k represent intermediate objects.
func makeTree(k ast.Ref, v *ast.Term) ast.Object {
var obj ast.Object
for i := len(k) - 1; i >= 1; i-- {
obj = ast.NewObject(ast.Item(k[i], v))
v = &ast.Term{Value: obj}
}
obj = ast.NewObject(ast.Item(k[0], v))
return obj
}