Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion custom_components/pyscript/decorators/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def create_expression(self, expression: str) -> None:
self.dm.name + " " + dec_name, self.dm.ast_ctx.global_ctx, self.dm.name
)
Function.install_ast_funcs(self._ast_expression)
self._ast_expression.parse(expression, mode="eval")
self._ast_expression.parse_trigger_expr(expression)

def has_expression(self) -> bool:
"""Return True if expression was created."""
Expand Down
14 changes: 10 additions & 4 deletions custom_components/pyscript/decorators/state.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@
from ..decorator import WaitUntilDecoratorManager
from ..decorator_abc import DecoratorManagerStatus, DispatchData, TriggerDecorator, TriggerHandlerDecorator
from ..state import State
from ..trigger import ident_any_values_changed, ident_values_changed
from ..trigger import (
any_trigger_exprs,
ident_any_values_changed,
ident_values_changed,
strip_trigger_expr,
)
from .base import AutoKwargsDecorator, ExpressionDecorator

STATE_RE = re.compile(r"\w+\.\w+(\.((\w+)|\*))?$")
Expand Down Expand Up @@ -116,16 +121,17 @@ async def validate(self) -> None:
state_trig = []

for trig in self.args:
if STATE_RE.match(trig):
self.state_trig_ident_any.add(trig)
name = strip_trigger_expr(trig)
if STATE_RE.match(name):
self.state_trig_ident_any.add(name)
else:
state_trig.append(trig)

if len(state_trig) > 0:
if len(state_trig) == 1:
state_trig_expr = state_trig[0]
else:
state_trig_expr = f"any([{', '.join(state_trig)}])"
state_trig_expr = any_trigger_exprs(state_trig)

self.create_expression(state_trig_expr)

Expand Down
87 changes: 86 additions & 1 deletion custom_components/pyscript/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -2415,6 +2415,88 @@ def parse(self, code_str: str | list[str], filename: str | None = None, mode: st
self.code_list = []
self.ast = ast.parse(self.code_str, filename=self.filename, mode=mode)

def parse_trigger_expr(self, expr: str) -> None:
r"""
Parse a trigger expression.

Blanks around it are stripped. If it still has a line break, it is parsed unstripped as
"(" + expr + "\n)", so it needs no brackets of its own and keeps its line numbers; positions
on its first line move back by the added "(". Nothing that is valid only because of the
added brackets is accepted; what parsed before (stripped) still parses as before.
"""
stripped = expr.strip(" \t\r\n") if isinstance(expr, str) else expr
if not isinstance(stripped, str) or ("\n" not in stripped and "\r" not in stripped):
self.parse(stripped, mode="eval")
return
self.ast = None
self.code_str = expr
# Python reads "\r\n" and "\r" as "\n"; joining with "\n" keeps the added ")" on a line of its own
self.code_list = expr.replace("\r\n", "\n").replace("\r", "\n").split("\n")
source = "\n".join(self.code_list)
try:
tree = ast.parse("(" + source + "\n)", filename=self.filename, mode="eval")
except SyntaxError as exc:
raise self._trigger_syntax_error(
exc.msg, exc.lineno, exc.offset, exc.end_lineno, exc.end_offset
) from None
top, msg = tree.body, None
if (top.lineno, top.col_offset) == (1, 0):
# Python's parser says it starts at the added "(", so it needs that bracket
if isinstance(top, ast.Tuple):
msg = "tuple must be inside brackets" if top.elts else "expression is empty"
elif isinstance(top, ast.GeneratorExp):
msg = "generator expression must be inside brackets"
else:
msg = "unmatched ')'"
elif isinstance(top, (ast.NamedExpr, ast.Yield, ast.YieldFrom)):
# a bare ":=" or yield is an error as a keyword value, a bracketed one isn't
try:
ast.parse("f(value=" + source + "\n)", mode="eval")
except SyntaxError:
msg = ("':='" if isinstance(top, ast.NamedExpr) else "'yield'") + " must be inside brackets"
if msg:
try:
ast.parse(stripped, mode="eval")
except SyntaxError:
# point at the first part of it that the user wrote
starts = [
(node.lineno, node.col_offset) for node in ast.walk(top) if hasattr(node, "lineno")
]
lineno, col = min((start for start in starts if start != (1, 0)), default=(1, 1))
raise self._trigger_syntax_error(msg, lineno, col + 1) from None
# valid without the added brackets, like "a, b" then a "# comment" line: parse it as before
self.parse(stripped, mode="eval")
return
for node in ast.walk(tree):
if getattr(node, "lineno", None) == 1:
node.col_offset -= 1
if getattr(node, "end_lineno", None) == 1:
node.end_col_offset -= 1
self.ast = tree

def _trigger_syntax_error(
self,
msg: str,
lineno: int | None,
offset: int | None,
end_lineno: int | None = None,
end_offset: int | None = None,
) -> SyntaxError:
r"""Return a SyntaxError, its position in "(" + expr + "\n)" moved onto the expression as written."""

def move(lineno: int, offset: int) -> tuple[int, int]:
if lineno > len(self.code_list):
# on the added ")": point at the end of the last line that isn't blank
lineno = max((idx for idx, line in enumerate(self.code_list, 1) if line.strip()), default=1)
return lineno, len(self.code_list[lineno - 1].rstrip())
return lineno, max(offset - (lineno == 1), 1)

start = move(lineno or 1, offset or 1)
end = move(end_lineno, end_offset or 1) if end_lineno else start
if end <= start:
end = (start[0], start[1] + 1)
return SyntaxError(msg, (self.filename, start[0], start[1], self.code_list[start[0] - 1], *end))

def log_exception(self, exc: Exception) -> None:
"""Log eval exception."""
try:
Expand Down Expand Up @@ -2586,7 +2668,10 @@ def _build_stack(self) -> None:
self.current_filename = eval_func.global_ctx.get_file_path()
elif code.co_qualname == AstEval.call_func.__qualname__ and self.current_func is None:
self.current_func = frame.f_locals.get("func_name", None)
elif code.co_qualname == AstEval.parse.__qualname__ and isinstance(self.exc, SyntaxError):
elif code.co_qualname in (
AstEval.parse.__qualname__,
AstEval.parse_trigger_expr.__qualname__,
) and isinstance(self.exc, SyntaxError):
ctx = frame.f_locals.get("self")
self.current_code_list = ctx.code_list
self.current_filename = ctx.global_ctx.get_file_path() or ctx.filename
Expand Down
47 changes: 32 additions & 15 deletions custom_components/pyscript/trigger.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,21 @@
STATE_RE = re.compile(r"\w+\.\w+(\.((\w+)|\*))?$")


def strip_trigger_expr(expr):
"""Strip surrounding whitespace from a trigger expression (non-strings are returned as is)."""
return expr.strip(" \t\r\n") if isinstance(expr, str) else expr


def any_trigger_exprs(exprs):
"""
Join trigger expressions into one any([...]) expression.

Each expression is stripped and goes on its own lines, so a trailing # comment can't swallow
the separator or the closing bracket that follow it.
"""
return "any([" + "\n,\n".join(strip_trigger_expr(expr) for expr in exprs) + "\n])"


def dt_now():
"""Return current time."""
return dt.datetime.now()
Expand Down Expand Up @@ -274,23 +289,24 @@ async def wait_until(
# on any change (no expr)
#
for trig in state_trigger:
if STATE_RE.match(trig):
state_trig_ident_any.add(trig)
name = strip_trigger_expr(trig)
if STATE_RE.match(name):
state_trig_ident_any.add(name)
else:
state_trig.append(trig)

if len(state_trig) > 0:
if len(state_trig) == 1:
state_trig_expr = state_trig[0]
else:
state_trig_expr = f"any([{', '.join(state_trig)}])"
state_trig_expr = any_trigger_exprs(state_trig)
state_trig_eval = AstEval(
f"{ast_ctx.name} state_trigger",
ast_ctx.get_global_ctx(),
logger_name=ast_ctx.get_logger_name(),
)
Function.install_ast_funcs(state_trig_eval)
state_trig_eval.parse(state_trig_expr, mode="eval")
state_trig_eval.parse_trigger_expr(state_trig_expr)
state_trig_ident = await state_trig_eval.get_names()

state_trig_ident.update(state_trig_ident_any)
Expand Down Expand Up @@ -336,7 +352,7 @@ async def wait_until(
)
Function.install_ast_funcs(event_trig_expr)
try:
event_trig_expr.parse(event_trigger[1], mode="eval")
event_trig_expr.parse_trigger_expr(event_trigger[1])
except:
if len(state_trig_ident) > 0:
State.notify_del(state_trig_ident, notify_q)
Expand All @@ -353,7 +369,7 @@ async def wait_until(
)
Function.install_ast_funcs(mqtt_trig_expr)
try:
mqtt_trig_expr.parse(mqtt_trigger[1], mode="eval")
mqtt_trig_expr.parse_trigger_expr(mqtt_trigger[1])
except:
if len(state_trig_ident) > 0:
State.notify_del(state_trig_ident, notify_q)
Expand All @@ -370,7 +386,7 @@ async def wait_until(
)
Function.install_ast_funcs(webhook_trig_expr)
try:
webhook_trig_expr.parse(webhook_trigger[1], mode="eval")
webhook_trig_expr.parse_trigger_expr(webhook_trigger[1])
except:
if len(state_trig_ident) > 0:
State.notify_del(state_trig_ident, notify_q)
Expand Down Expand Up @@ -916,7 +932,7 @@ def __init__(
f"{self.name} @state_active()", self.global_ctx, logger_name=self.name
)
Function.install_ast_funcs(self.active_expr)
self.active_expr.parse(self.state_active, mode="eval")
self.active_expr.parse_trigger_expr(self.state_active)

if "time_trigger" in trig_cfg and self.time_trigger is None:
self.run_on_startup = True
Expand All @@ -942,22 +958,23 @@ def __init__(
# on any change (no expr)
#
for trig in triggers:
if STATE_RE.match(trig):
self.state_trig_ident_any.add(trig)
name = strip_trigger_expr(trig)
if STATE_RE.match(name):
self.state_trig_ident_any.add(name)
else:
state_trig.append(trig)

if len(state_trig) > 0:
if len(state_trig) == 1:
self.state_trig_expr = state_trig[0]
else:
self.state_trig_expr = f"any([{', '.join(state_trig)}])"
self.state_trig_expr = any_trigger_exprs(state_trig)
self.state_trig_eval = AstEval(
f"{self.name} @state_trigger()", self.global_ctx, logger_name=self.name
)
Function.install_ast_funcs(self.state_trig_eval)
try:
self.state_trig_eval.parse(self.state_trig_expr, mode="eval")
self.state_trig_eval.parse_trigger_expr(self.state_trig_expr)
except Exception as exc:
self.state_trig_eval.log_exception(exc)
return
Expand All @@ -972,7 +989,7 @@ def __init__(
)
Function.install_ast_funcs(self.event_trig_expr)
try:
self.event_trig_expr.parse(self.event_trigger[1], mode="eval")
self.event_trig_expr.parse_trigger_expr(self.event_trigger[1])
except Exception as exc:
self.event_trig_expr.log_exception(exc)
return
Expand All @@ -987,7 +1004,7 @@ def __init__(
)
Function.install_ast_funcs(self.mqtt_trig_expr)
try:
self.mqtt_trig_expr.parse(self.mqtt_trigger[1], mode="eval")
self.mqtt_trig_expr.parse_trigger_expr(self.mqtt_trigger[1])
except Exception as exc:
self.mqtt_trig_expr.log_exception(exc)
return
Expand All @@ -1002,7 +1019,7 @@ def __init__(
)
Function.install_ast_funcs(self.webhook_trig_expr)
try:
self.webhook_trig_expr.parse(self.webhook_trigger[1], mode="eval")
self.webhook_trig_expr.parse_trigger_expr(self.webhook_trigger[1])
except Exception as exc:
self.webhook_trig_expr.log_exception(exc)
return
Expand Down
18 changes: 18 additions & 0 deletions docs/reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,24 @@ The trigger can include arguments with any mixture of string expressions (that a
when any of the underlying state variables change) and string state variable or attribute
names (that trigger whenever that variable or attribute changes).

A trigger expression may start or end with spaces, tabs or new lines, which are ignored. An
expression written over several lines, for example in a triple-quoted string, is read as if it were
inside brackets, so it needs no brackets of its own, and any of its lines can end with a
``# comment``:

.. code:: python

@state_trigger("""
binary_sensor.motion == 'off' and # nobody there
light.porch == 'on'
""")

An expression over several lines can't rely on those brackets for anything else: a bare generator
expression (forgetting the ``any()`` around ``x == 1 for x in ...``), a bare tuple that needs them
for its line break, an empty expression, or a bare ``:=`` or ``yield`` gives a ``SyntaxError``.
Inside brackets of your own they work as they do in Python. The same goes for ``@state_active``, ``task.wait_until`` and the
expressions of ``@event_trigger``, ``@mqtt_trigger``, ``@webhook_trigger`` and ``@webhook_handler``.

Note that if a state variable and attributes are set to the same value, HASS doesn't generate a
state change event, so the ``@state_trigger`` condition will not be checked. It is only evaluated
each time a state variable or any of its attributes change to a new value.
Expand Down
59 changes: 59 additions & 0 deletions tests/decorators/test_webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -397,3 +397,62 @@ def webhook_dup_b(**_):
pass
""")
await pyscript.wait_exception(ValueError, match="Handler is already defined")


@pytest.mark.asyncio
@pytest.mark.parametrize("legacy", [False, True])
async def test_webhook_trigger_expression_over_several_lines(pyscript, hass, legacy):
"""A webhook trigger expression can start with blanks and run over several lines without brackets."""
pyscript.config = {DOMAIN: {CONF_LEGACY_DECORATORS: legacy}}
await pyscript.start("""
@webhook_trigger("lines_hook", '''
payload.get('a') == 1 and # first
payload.get('b') == 2
''')
def webhook_lines(payload):
pyscript.done = payload

@webhook_trigger("start_wait_hook")
def webhook_wait(payload):
task.wait_until(webhook_trigger=["wait_hook", "\\n payload.get('c') == 3 or\\n payload.get('c') == 4\\n"])
pyscript.done = "waited"
""")

def json_request(body: bytes) -> MockRequest:
return _request(body=body, headers={"Content-Type": "application/json"})

await webhook.async_handle_webhook(hass, "lines_hook", json_request(b'{"a": 1, "b": 0}'))
await hass.async_block_till_done()
assert pyscript.done.empty()
await webhook.async_handle_webhook(hass, "lines_hook", json_request(b'{"a": 1, "b": 2}'))
await pyscript.wait_done({"a": 1, "b": 2})

await webhook.async_handle_webhook(hass, "start_wait_hook", json_request(b"{}"))
for _ in range(100):
if not pyscript.done.empty():
break
await webhook.async_handle_webhook(hass, "wait_hook", json_request(b'{"c": 4}'))
await asyncio.sleep(0.02)
await pyscript.wait_done("waited")


@pytest.mark.asyncio
async def test_webhook_handler_expression_over_several_lines(pyscript, hass):
"""A @webhook_handler expression can start with blanks and run over several lines without brackets."""
await pyscript.start("""
@webhook_handler("lines_handler", '''
payload.get('token') == 'secret' and
payload.get('user') == 'me' # both
''')
def webhook_lines_handler(payload, **_):
return {"ok": True}
""")

for body, status in (
(b'{"token": "secret", "user": "you"}', 403),
(b'{"token": "secret", "user": "me"}', 200),
):
response = await webhook.async_handle_webhook(
hass, "lines_handler", _request(body=body, headers={"Content-Type": "application/json"})
)
assert response.status == status
Loading
Loading