Skip to content

Commit c0c291c

Browse files
ntdatt812claude
andcommitted
fix(workflows): flag an unterminated {{ and quote the correction safely
Two gaps in the condition validator, both raised in review. An opening `{{` with no `}}` after it is never substituted either: _interpolate_expressions takes its `raw_close == -1` branch and appends the tail verbatim. So `condition: "{{ inputs.count > 100"` -- and the reversed `"}} inputs.count > 100 {{"`, whose only `{{` is last -- come back unchanged and are coerced to true exactly like a brace-less string. The helper now looks for a complete block rather than an opening one. The suggested correction was interpolated into a double-quoted scalar, so a condition containing a double quote produced YAML that does not parse: `condition: "{{ inputs.name == "zzz" }}"` raises a ParserError. format_condition_correction() now picks the quoting from the content and drops a stray delimiter instead of nesting a second one, so the message stays paste-ready. All three validators share it. Tests: 30 more cases -- the incomplete forms, and a YAML round trip over conditions holding single quotes, double quotes, both, and backslashes, asserting each correction loads back exactly and is not re-flagged. Co-Authored-By: Claude Opus 5 <[email protected]>
1 parent 0fa9e87 commit c0c291c

5 files changed

Lines changed: 132 additions & 11 deletions

File tree

‎src/specify_cli/workflows/expressions.py‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -716,4 +716,37 @@ def condition_is_never_evaluated(condition: Any) -> bool:
716716
stripped = condition.strip()
717717
if not stripped or stripped.lower() in ("true", "false"):
718718
return False
719-
return "{{" not in stripped
719+
open_at = stripped.find("{{")
720+
if open_at == -1:
721+
return True
722+
# An opening ``{{`` with no ``}}`` anywhere after it is never substituted
723+
# either: ``_interpolate_expressions`` takes its ``raw_close == -1`` branch
724+
# and appends the tail verbatim. So ``{{ inputs.count > 100`` -- and the
725+
# reversed ``}} inputs.count > 100 {{``, whose only ``{{`` is last -- come
726+
# back unchanged and are just as silently true as a brace-less string.
727+
return stripped.find("}}", open_at + 2) == -1
728+
729+
730+
def format_condition_correction(condition: Any) -> str:
731+
"""Render *condition* wrapped in ``{{ }}`` as a quoted, paste-ready YAML scalar.
732+
733+
The validators hand this back as the corrected form, so it has to survive a
734+
round trip through a YAML parser. A plain ``"{{ ... }}"`` does not: a
735+
condition holding a double quote (``inputs.name == "zzz"``) closes the
736+
scalar early and the workflow file no longer loads. Quoting is therefore
737+
chosen from the content -- double by default, single when the expression
738+
itself contains a double quote, and double with backslash escapes when it
739+
contains both.
740+
741+
A stray delimiter is dropped rather than nested: ``{{ inputs.count > 100``
742+
corrects to ``"{{ inputs.count > 100 }}"``, not to a doubled ``{{ {{ ... }} }}``.
743+
"""
744+
core = str(condition).strip()
745+
core = re.sub(r"^\s*(\{\{|\}\})\s*", "", core)
746+
core = re.sub(r"\s*(\{\{|\}\})\s*$", "", core).strip()
747+
wrapped = "{{ " + core + " }}"
748+
if '"' not in wrapped and "\\" not in wrapped:
749+
return '"' + wrapped + '"'
750+
if "'" not in wrapped:
751+
return "'" + wrapped + "'"
752+
return '"' + wrapped.replace("\\", "\\\\").replace('"', '\\"') + '"'

‎src/specify_cli/workflows/steps/do_while/__init__.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@
55
from typing import Any
66

77
from specify_cli.workflows.base import StepBase, StepContext, StepResult, StepStatus
8-
from specify_cli.workflows.expressions import condition_is_never_evaluated
8+
from specify_cli.workflows.expressions import (
9+
condition_is_never_evaluated,
10+
format_condition_correction,
11+
)
912

1013

1114
class DoWhileStep(StepBase):
@@ -99,9 +102,9 @@ def validate(self, config: dict[str, Any]) -> list[str]:
99102
# to write by habit.
100103
errors.append(
101104
f"Do-while step {config.get('id', '?')!r}: 'condition' "
102-
f"{config['condition']!r} has no '{{{{ }}}}' block, so it is never "
103-
"evaluated and is always true. Wrap the expression: "
104-
'"{{ ' + str(config["condition"]).strip() + ' }}".'
105+
f"{config['condition']!r} has no complete '{{{{ }}}}' block, so it is "
106+
"never evaluated and is always true. Wrap the expression: "
107+
+ format_condition_correction(config["condition"]) + "."
105108
)
106109
max_iter = config.get("max_iterations")
107110
if max_iter is not None:

‎src/specify_cli/workflows/steps/if_then/__init__.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from specify_cli.workflows.base import StepBase, StepContext, StepResult, StepStatus
88
from specify_cli.workflows.expressions import (
99
condition_is_never_evaluated,
10+
format_condition_correction,
1011
evaluate_condition,
1112
)
1213

@@ -92,9 +93,9 @@ def validate(self, config: dict[str, Any]) -> list[str]:
9293
# to write by habit.
9394
errors.append(
9495
f"If step {config.get('id', '?')!r}: 'condition' "
95-
f"{config['condition']!r} has no '{{{{ }}}}' block, so it is never "
96-
"evaluated and is always true. Wrap the expression: "
97-
'"{{ ' + str(config["condition"]).strip() + ' }}".'
96+
f"{config['condition']!r} has no complete '{{{{ }}}}' block, so it is "
97+
"never evaluated and is always true. Wrap the expression: "
98+
+ format_condition_correction(config["condition"]) + "."
9899
)
99100
if "then" not in config:
100101
errors.append(

‎src/specify_cli/workflows/steps/while_loop/__init__.py‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from specify_cli.workflows.base import StepBase, StepContext, StepResult, StepStatus
88
from specify_cli.workflows.expressions import (
99
condition_is_never_evaluated,
10+
format_condition_correction,
1011
evaluate_condition,
1112
)
1213

@@ -110,9 +111,9 @@ def validate(self, config: dict[str, Any]) -> list[str]:
110111
# to write by habit.
111112
errors.append(
112113
f"While step {config.get('id', '?')!r}: 'condition' "
113-
f"{config['condition']!r} has no '{{{{ }}}}' block, so it is never "
114-
"evaluated and is always true. Wrap the expression: "
115-
'"{{ ' + str(config["condition"]).strip() + ' }}".'
114+
f"{config['condition']!r} has no complete '{{{{ }}}}' block, so it is "
115+
"never evaluated and is always true. Wrap the expression: "
116+
+ format_condition_correction(config["condition"]) + "."
116117
)
117118
max_iter = config.get("max_iterations")
118119
if max_iter is not None:

‎tests/unit/test_condition_expression_block.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
"""A string condition with no ``{{ }}`` block is never evaluated (always true)."""
22

33
import pytest
4+
import yaml
45

56
from specify_cli.workflows.base import StepContext
67
from specify_cli.workflows.expressions import (
78
condition_is_never_evaluated,
89
evaluate_condition,
10+
format_condition_correction,
911
)
1012
from specify_cli.workflows.steps.do_while import DoWhileStep
1113
from specify_cli.workflows.steps.if_then import IfThenStep
@@ -65,3 +67,84 @@ def test_validator_accepts_evaluated_and_literal_conditions(step_cls, condition)
6567
)
6668
def test_condition_is_never_evaluated(value, expected):
6769
assert condition_is_never_evaluated(value) is expected
70+
71+
72+
# --- An unterminated ``{{`` is the same defect, not a different one -----------
73+
#
74+
# ``_interpolate_expressions`` substitutes nothing when no ``}}`` follows the
75+
# opening ``{{`` (its ``raw_close == -1`` branch appends the tail verbatim), so
76+
# ``{{ inputs.count > 100`` is returned unchanged and coerced to true exactly
77+
# like a brace-less string.
78+
79+
BACKSLASH = chr(92)
80+
81+
NEVER_EVALUATED = [
82+
"inputs.count > 100", # no delimiter at all
83+
"{{ inputs.count > 100", # opened, never closed
84+
"}} inputs.count > 100 {{", # reversed: the only '{{' is last
85+
]
86+
87+
88+
@pytest.mark.parametrize("condition", NEVER_EVALUATED)
89+
def test_incomplete_block_is_silently_true_and_is_flagged(condition):
90+
ctx = StepContext(inputs={"count": 5, "name": "abc"})
91+
assert evaluate_condition(condition, ctx) is True
92+
assert condition_is_never_evaluated(condition) is True
93+
94+
95+
@pytest.mark.parametrize(
96+
"condition",
97+
[
98+
"{{ inputs.count > 100 }}",
99+
"{{ inputs.a }} and {{ inputs.b }}",
100+
"{{ inputs.text | default('}}') }}", # literal '}}' inside an argument
101+
],
102+
)
103+
def test_complete_block_is_not_flagged(condition):
104+
assert condition_is_never_evaluated(condition) is False
105+
106+
107+
# --- The suggested correction has to survive a YAML round trip ---------------
108+
109+
TRICKY_CONDITIONS = [
110+
"inputs.count > 100",
111+
'inputs.name == "zzz"', # double quote
112+
"inputs.name == 'zzz'", # single quote
113+
'inputs.a == "x" and inputs.b == \'y\'', # both
114+
"inputs.path == 'C:" + BACKSLASH + "tmp'", # backslash
115+
'inputs.path == "C:' + BACKSLASH + 'tmp"', # backslash + quote
116+
'{{ inputs.name == "zzz"', # incomplete + quote
117+
"}} inputs.count > 100 {{",
118+
]
119+
120+
121+
@pytest.mark.parametrize("condition", TRICKY_CONDITIONS)
122+
def test_correction_is_valid_yaml_and_round_trips(condition):
123+
"""A correction the author cannot paste into their workflow is no correction."""
124+
loaded = yaml.safe_load("condition: " + format_condition_correction(condition))
125+
stripped = condition.strip().lstrip("{}").rstrip("{}").strip()
126+
assert loaded["condition"] == "{{ " + stripped + " }}"
127+
128+
129+
@pytest.mark.parametrize("condition", TRICKY_CONDITIONS)
130+
def test_correction_does_not_trip_the_validator_again(condition):
131+
loaded = yaml.safe_load("condition: " + format_condition_correction(condition))
132+
assert condition_is_never_evaluated(loaded["condition"]) is False
133+
134+
135+
@pytest.mark.parametrize("condition", ["{{ inputs.count > 100", "}} a > 1 {{"])
136+
def test_correction_replaces_a_stray_delimiter_instead_of_nesting_one(condition):
137+
corrected = format_condition_correction(condition)
138+
assert "{{ {{" not in corrected and "}} }}" not in corrected
139+
assert corrected.count("{{") == 1 and corrected.count("}}") == 1
140+
141+
142+
@pytest.mark.parametrize("step_cls", STEP_CLASSES)
143+
@pytest.mark.parametrize("condition", ['inputs.name == "zzz"', "{{ inputs.count > 100"])
144+
def test_validator_correction_is_yaml_safe(step_cls, condition):
145+
config = {"id": "s1", "condition": condition, "then": [], "steps": []}
146+
errors = [e for e in step_cls().validate(config) if "never evaluated" in e]
147+
assert len(errors) == 1
148+
suggested = errors[0].split("Wrap the expression: ", 1)[1].rstrip(".")
149+
loaded = yaml.safe_load("condition: " + suggested)
150+
assert condition_is_never_evaluated(loaded["condition"]) is False

0 commit comments

Comments
 (0)