Skip to content

Commit

Permalink
cue: add Value.lookup
Browse files Browse the repository at this point in the history
Implement lookup.

Updates #3100.
Updates #3074.

Signed-off-by: Aram Hăvărneanu <[email protected]>
Change-Id: I8b8c83cd244e93730eda7826bbb222a0ec496650
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue-py/+/1194802
Reviewed-by: Daniel Martí <[email protected]>
TryBot-Result: CUEcueckoo <[email protected]>
  • Loading branch information
4ad committed Jun 3, 2024
1 parent 45eb8cf commit 86ee960
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
21 changes: 21 additions & 0 deletions cue/value.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,18 @@ def unify(self, other: 'Value') -> 'Value':
v = libcue.unify(self._val, other._val)
return Value(self._ctx, v)

def lookup(self, path: str) -> 'Value':
"""
Return the CUE value at path.
Args:
path: CUE path relative to self.
Returns:
Value: the value reached at path, starting from self.
"""
return _lookup(self, path)

def to_int(self) -> int:
"""
Convert CUE value to integer.
Expand Down Expand Up @@ -278,3 +290,12 @@ def _to_json(val: Value) -> str:
s = dec.decode("utf-8")
libcue.libc_free(buf_ptr[0])
return s

def _lookup(val: Value, path: str) -> Value:
val_ptr = libcue.ffi.new("cue_value*")
path_ptr = libcue.ffi.new("char[]", path.encode("utf-8"))

err = libcue.lookup_string(val._val, path_ptr, val_ptr)
if err != 0:
raise Error(err)
return Value(val._ctx, val_ptr[0])
10 changes: 10 additions & 0 deletions tests/test_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,3 +139,13 @@ def test_decode_error():

with pytest.raises(cue.Error):
ctx.compile("false").to_unsigned()

def test_lookup():
ctx = cue.Context()

val = ctx.compile("x: true")
assert val.lookup("x").to_bool() == True

val = ctx.compile(r'x: y: { a: 1, b: "hello"}')
assert val.lookup("x").lookup("y").lookup("b").to_str() == "hello"
assert val.lookup("x.y.a").to_int() == 1

0 comments on commit 86ee960

Please sign in to comment.