Skip to content

Commit

Permalink
cue: add Value.default
Browse files Browse the repository at this point in the history
Implement extraction of default values from CUE values.

Updates #3100.
Updates #3074.

Signed-off-by: Aram Hăvărneanu <[email protected]>
Change-Id: Ia4e3ea639658018c38e1c510cba86fec83274aa5
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue-py/+/1194803
Reviewed-by: Daniel Martí <[email protected]>
TryBot-Result: CUEcueckoo <[email protected]>
  • Loading branch information
4ad committed Jun 3, 2024
1 parent 86ee960 commit f496ef5
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
18 changes: 17 additions & 1 deletion cue/value.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
Perform operations on CUE values.
"""

from typing import Any, final
from typing import Any, Optional, final
from cue.error import Error
import libcue

Expand Down Expand Up @@ -215,6 +215,15 @@ def to_json(self) -> str:

return _to_json(self)

def default(self) -> Optional['Value']:
"""
Return default value.
Returns:
Optional[Value]: the default value, if it exists, or None otherwise.
"""
return _default(self)

def _to_int(val: Value) -> int:
ptr = libcue.ffi.new("int64_t*")
err = libcue.dec_int64(val._val, ptr)
Expand Down Expand Up @@ -299,3 +308,10 @@ def _lookup(val: Value, path: str) -> Value:
if err != 0:
raise Error(err)
return Value(val._ctx, val_ptr[0])

def _default(val: Value) -> Optional[Value]:
ok_ptr = libcue.ffi.new("bool*")
res = libcue.default(val._val, ok_ptr)
if ok_ptr[0] == 1:
return Value(val._ctx, res)
return None
18 changes: 18 additions & 0 deletions tests/test_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,21 @@ def test_lookup():
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

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

v = ctx.compile("int")
assert v.default() == None

v = ctx.compile("1")
assert v.default() == None

v = ctx.compile("int | *1")
assert v.default() == ctx.to_value(1)

v = ctx.compile(r'string | *"hello"')
assert v.default() == ctx.to_value("hello")

v = ctx.compile(r'(int | *1) & 2')
assert v.default() == None

0 comments on commit f496ef5

Please sign in to comment.