-
Notifications
You must be signed in to change notification settings - Fork 122
/
eval.go
82 lines (64 loc) · 1.56 KB
/
eval.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
// Copyright 2021-2024 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
package internal
import (
"errors"
"fmt"
"github.com/pterm/pterm"
"github.com/cerbos/cerbos/internal/printer/colored"
)
var errEvalErrorPresent = errors.New("failed expression(s) present")
type evalOutput struct {
tree pterm.LeveledList
level int
}
func (eo *evalOutput) append(text string) {
eo.tree = append(eo.tree, pterm.LeveledListItem{Level: eo.level, Text: text})
}
func (eo *evalOutput) appendAndLevelUp(text string) {
eo.append(text)
eo.level++
}
func buildEvalOutput(e *eval) *evalOutput {
eo := &evalOutput{level: 0}
doBuildEvalOutput(eo, e)
return eo
}
func successText(success bool) string {
if success {
return colored.REPLSuccess("true")
}
return colored.REPLError("false")
}
func doBuildEvalOutput(eo *evalOutput, e *eval) {
switch e.evalType {
case evalTypeExpr:
eo.append(fmt.Sprintf("%s [%v]", colored.REPLExpr(e.expr), successText(e.success)))
case evalTypeAny, evalTypeAll, evalTypeNone:
eo.appendAndLevelUp(fmt.Sprintf("%s [%v]", e.evalType, successText(e.success)))
for _, ev := range e.evals {
doBuildEvalOutput(eo, ev)
}
}
}
type evalType string
const (
evalTypeAll evalType = "all"
evalTypeAny evalType = "any"
evalTypeExpr evalType = "expr"
evalTypeNone evalType = "none"
)
type eval struct {
err error
evalType evalType
expr string
evals []*eval
success bool
}
func (e *eval) append(eval *eval) {
if eval.err != nil || !eval.success {
e.err = errEvalErrorPresent
e.success = false
}
e.evals = append(e.evals, eval)
}