policy: add a global boolean to enable tracing on policy matching

This commit is contained in:
Michael Muré
2024-11-07 10:43:01 +01:00
parent 884d63a689
commit b05a136b81

View File

@@ -9,6 +9,9 @@ import (
"github.com/ipld/go-ipld-prime/must"
)
// MatchTrace, if set, will print tracing statements to stdout of the policy matching resolution.
var MatchTrace = false
// Match determines if the IPLD node satisfies the policy.
func (p Policy) Match(node datamodel.Node) bool {
for _, stmt := range p {
@@ -59,7 +62,7 @@ const (
// - matchResultNoData: if the selector didn't match the expected data.
// For matchResultTrue and matchResultNoData, the leaf-most (innermost) statement failing to be true is returned,
// as well as the corresponding root-most encompassing statement.
func matchStatement(cur Statement, node ipld.Node) (_ matchResult, leafMost Statement) {
func matchStatement(cur Statement, node ipld.Node) (output matchResult, leafMost Statement) {
var boolToRes = func(v bool) (matchResult, Statement) {
if v {
return matchResultTrue, nil
@@ -67,6 +70,11 @@ func matchStatement(cur Statement, node ipld.Node) (_ matchResult, leafMost Stat
return matchResultFalse, cur
}
}
if MatchTrace {
defer func() {
fmt.Printf("match %v --> %v\n", cur, matchResToStr(output))
}()
}
switch cur.Kind() {
case KindEqual:
@@ -274,3 +282,18 @@ func gt(order int) bool { return order == 1 }
func gte(order int) bool { return order == 0 || order == 1 }
func lt(order int) bool { return order == -1 }
func lte(order int) bool { return order == 0 || order == -1 }
func matchResToStr(res matchResult) string {
switch res {
case matchResultTrue:
return "True"
case matchResultFalse:
return "False"
case matchResultNoData:
return "NoData"
case matchResultOptionalNoData:
return "OptionalNoData"
default:
panic("invalid matchResult")
}
}