Merge pull request #669 from santhreal/fix/extract-code-block-optional-newline

fix(visualize): allow code fences without a blank closing line
This commit is contained in:
Bingxi Zhao
2026-07-23 22:26:14 +08:00
committed by GitHub
3 changed files with 19 additions and 2 deletions

View File

@@ -38,10 +38,11 @@ def extract_code_block(text: str, language: str = "") -> str:
If *language* is given the block must start with that tag;
otherwise any triple-backtick fence is accepted.
"""
# Closing fence may sit on the same line as the last content line.
if language:
pattern = rf"```{re.escape(language)}\s*\n([\s\S]*?)\n```"
pattern = rf"```{re.escape(language)}\s*\n([\s\S]*?)\n?```"
else:
pattern = r"```[A-Za-z]*\s*\n([\s\S]*?)\n```"
pattern = r"```[A-Za-z]*\s*\n([\s\S]*?)\n?```"
match = re.search(pattern, text or "", re.IGNORECASE)
if match:
return match.group(1).strip()

View File

View File

@@ -0,0 +1,16 @@
"""Regression tests for visualize.utils.extract_code_block."""
from __future__ import annotations
from deeptutor.agents.visualize.utils import extract_code_block
def test_extract_code_block_closing_fence_without_leading_newline() -> None:
raw = "```mermaid\ngraph TD\n A-->B```"
assert extract_code_block(raw, "mermaid") == "graph TD\n A-->B"
assert extract_code_block(raw) == "graph TD\n A-->B"
def test_extract_code_block_normal_fenced_block() -> None:
raw = "```javascript\nconst x = 1;\n```"
assert extract_code_block(raw, "javascript") == "const x = 1;"