Skip to content

Commit 90b3d33

Browse files
committed
Preventing situations where a function does not yield even once
1 parent e117e3e commit 90b3d33

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

adafruit_templateengine.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ def _replace_amp_or_semi(match: re.Match):
195195
)
196196
_TOKEN_PATTERN = re.compile(r"{{ .+? }}|{% .+? %}")
197197
_LSTRIP_BLOCK_PATTERN = re.compile(r"\n +$")
198+
_YIELD_PATTERN = re.compile(r"\n +yield ")
198199

199200

200201
def _find_extends(template: str):
@@ -233,6 +234,10 @@ def _token_is_on_own_line(text_before_token: str) -> bool:
233234
return _LSTRIP_BLOCK_PATTERN.search(text_before_token) is not None
234235

235236

237+
def _contains_any_yield_statement(function_def: str) -> bool:
238+
return _YIELD_PATTERN.search(function_def) is not None
239+
240+
236241
def _exists_and_is_file(path: str) -> bool:
237242
try:
238243
return (os.stat(path)[0] & 0b_11110000_00000000) == 0b_10000000_00000000
@@ -657,6 +662,10 @@ def indented(fragment: str, end: str = "\n") -> str:
657662

658663
function_def += indented(f"yield {repr(text_after_last_token)}")
659664

665+
# Make sure the function definition contains at least one yield statement
666+
if not _contains_any_yield_statement(function_def):
667+
function_def += indented('yield ""')
668+
660669
# Create and return the template function
661670
exec(function_def) # pylint: disable=exec-used
662671
return locals()[function_name]
@@ -669,15 +678,18 @@ def _yield_as_sized_chunks(
669678

670679
# Yield chunks with a given size
671680
chunk = ""
681+
already_yielded = False
682+
672683
for item in generator:
673684
chunk += item
674685

675686
if chunk_size <= len(chunk):
676687
yield chunk[:chunk_size]
677688
chunk = chunk[chunk_size:]
689+
already_yielded = True
678690

679691
# Yield the last chunk
680-
if chunk:
692+
if chunk or not already_yielded:
681693
yield chunk
682694

683695

0 commit comments

Comments
 (0)