Files
releases/internal/ref/ref.go
T
Charlie Egan 301efc6997 Alter object.get to support nested key array
This commit extends the go and wasm implementations of object.get to
allow a key to also be an array.

When passed an array, each element in the array will be used as a key in
turn. This allows values at deeply nested paths to be extracted from
objects.

It also supports getting indexes of nested arrays.

The functionality was originally inspired by Ruby's Hash.dig function:
https://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig however
we opted to include the behavior in object.get instead after being
uncertain 'dig' was a commonly understood name.

Signed-off-by: Charlie Egan <charlieegan3@users.noreply.github.com>
2022-01-27 22:01:01 +01:00

40 lines
938 B
Go

// Copyright 2020 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 ref implements internal helpers for references
package ref
import (
"errors"
"strings"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/storage"
)
// ParseDataPath returns a ref from the slash separated path s rooted at data.
// All path segments are treated as identifier strings.
func ParseDataPath(s string) (ast.Ref, error) {
s = "/" + strings.TrimPrefix(s, "/")
path, ok := storage.ParsePath(s)
if !ok {
return nil, errors.New("invalid path")
}
return path.Ref(ast.DefaultRootDocument), nil
}
// ArrayPath will take an ast.Array and build an ast.Ref using the ast.Terms in the Array
func ArrayPath(a *ast.Array) ast.Ref {
var ref ast.Ref
a.Foreach(func(term *ast.Term) {
ref = append(ref, term)
})
return ref
}