feat: added abspath to jexpr
This commit is contained in:
parent
c33e5316bd
commit
cc8aafb300
|
@ -1,3 +1,4 @@
|
|||
import os
|
||||
from typing import Any, cast, Callable, Final
|
||||
import json
|
||||
|
||||
|
@ -8,34 +9,35 @@ Json = Any
|
|||
Builtin = Callable[..., Json]
|
||||
|
||||
BUILTINS: Final[dict[str, Builtin]] = {
|
||||
"uname": lambda arg: getattr(shell.uname(), arg).lower(),
|
||||
"include": lambda arg: evalRead(arg),
|
||||
"evalRead": lambda arg: evalRead(arg),
|
||||
"join": lambda lhs, rhs: cast(Json, {**lhs, **rhs} if isinstance(lhs, dict) else lhs + rhs),
|
||||
"concat": lambda *args: "".join(args),
|
||||
"eval": lambda arg: eval(arg),
|
||||
"read": lambda arg: read(arg),
|
||||
"exec": lambda *args: shell.popen(*args).splitlines(),
|
||||
"latest": lambda arg: shell.latest(arg),
|
||||
"uname": lambda arg, ctx: getattr(shell.uname(), arg).lower(),
|
||||
"include": lambda arg, ctx: evalRead(arg),
|
||||
"evalRead": lambda arg, ctx: evalRead(arg),
|
||||
"join": lambda lhs, rhs, ctx: cast(Json, {**lhs, **rhs} if isinstance(lhs, dict) else lhs + rhs),
|
||||
"concat": lambda *args, ctx: "".join(args),
|
||||
"eval": lambda arg, ctx: eval(arg),
|
||||
"read": lambda arg, ctx: read(arg),
|
||||
"exec": lambda *args, ctx: shell.popen(*args).splitlines(),
|
||||
"latest": lambda arg, ctx: shell.latest(arg),
|
||||
"abspath": lambda *args, ctx: os.path.normpath(os.path.join(os.path.dirname(ctx["filepath"]), *args))
|
||||
}
|
||||
|
||||
|
||||
def eval(jexpr: Json) -> Json:
|
||||
def eval(jexpr: Json, filePath: str) -> Json:
|
||||
if isinstance(jexpr, dict):
|
||||
result = {}
|
||||
for k in cast(dict[str, Json], jexpr):
|
||||
result[k] = eval(jexpr[k])
|
||||
result[k] = eval(jexpr[k], filePath)
|
||||
return cast(Json, result)
|
||||
elif isinstance(jexpr, list):
|
||||
jexpr = cast(list[Json], jexpr)
|
||||
if len(jexpr) > 0 and isinstance(jexpr[0], str) and jexpr[0].startswith("@"):
|
||||
funcName = jexpr[0][1:]
|
||||
if funcName in BUILTINS:
|
||||
return BUILTINS[funcName](*eval(jexpr[1:]))
|
||||
return BUILTINS[funcName](*eval(jexpr[1:], filePath), ctx={"filepath": filePath})
|
||||
|
||||
raise RuntimeError(f"Unknown macro {funcName}")
|
||||
else:
|
||||
return list(map(eval, jexpr))
|
||||
return list(map(lambda j: eval(j, filePath), jexpr))
|
||||
else:
|
||||
return jexpr
|
||||
|
||||
|
@ -51,4 +53,4 @@ def read(path: str) -> Json:
|
|||
def evalRead(path: str) -> Json:
|
||||
data = read(path)
|
||||
ensureSupportedManifest(data, path)
|
||||
return eval(data)
|
||||
return eval(data, path)
|
||||
|
|
Loading…
Reference in a new issue