From 6849124d22ec3aa984ff8220266c930c581dfa76 Mon Sep 17 00:00:00 2001 From: Stephen Rosen Date: Mon, 7 Oct 2024 17:30:01 -0500 Subject: [PATCH] reStructuredText: gracefully ignore empty code blocks (#369) Co-authored-by: Adam Johnson --- CHANGELOG.rst | 4 ++++ src/blacken_docs/__init__.py | 4 ++++ tests/test_blacken_docs.py | 27 +++++++++++++++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 3ebac7b..360f86a 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -2,6 +2,10 @@ Changelog ========= +* reStructuredText: Gracefully ignore empty code blocks. + + Thanks to Stephen Rosen in `PR #368 `__. + * Drop Python 3.8 support. * Support Python 3.13. diff --git a/src/blacken_docs/__init__.py b/src/blacken_docs/__init__.py index 08fe5e9..1e1aa8c 100644 --- a/src/blacken_docs/__init__.py +++ b/src/blacken_docs/__init__.py @@ -159,6 +159,8 @@ def _rst_match(match: Match[str]) -> str: lang = match["lang"] if lang is not None and lang not in PYGMENTS_PY_LANGS: return match[0] + if not match["code"].strip(): + return match[0] min_indent = min(INDENT_RE.findall(match["code"])) trailing_ws_match = TRAILING_NL_RE.search(match["code"]) assert trailing_ws_match @@ -240,6 +242,8 @@ def _rst_pycon_match(match: Match[str]) -> str: if _within_off_range(match.span()): return match[0] code = _pycon_match(match) + if not code.strip(): + return match[0] min_indent = min(INDENT_RE.findall(match["code"])) code = textwrap.indent(code, min_indent) return f'{match["before"]}{code}' diff --git a/tests/test_blacken_docs.py b/tests/test_blacken_docs.py index 9df0838..18bdbe4 100644 --- a/tests/test_blacken_docs.py +++ b/tests/test_blacken_docs.py @@ -534,6 +534,12 @@ def test_format_src_rst(): ) +def test_format_src_rst_empty(): + before = "some text\n\n.. code-block:: python\n\n\nsome other text\n" + after, _ = blacken_docs.format_str(before, BLACK_MODE) + assert after == before + + def test_format_src_rst_literal_blocks(): before = dedent( """\ @@ -560,6 +566,21 @@ def test_format_src_rst_literal_blocks(): ) +def test_format_src_rst_literal_block_empty(): + before = dedent( + """\ + hello:: + world + """ + ) + after, _ = blacken_docs.format_str( + before, + BLACK_MODE, + rst_literal_blocks=True, + ) + assert after == before + + def test_format_src_rst_literal_blocks_nested(): before = dedent( """ @@ -1323,3 +1344,9 @@ def test_format_src_rst_pycon_comments(): ) after, _ = blacken_docs.format_str(before, BLACK_MODE) assert after == before + + +def test_format_src_rst_pycon_empty(): + before = "some text\n\n.. code-block:: pycon\n\n\nsome other text\n" + after, _ = blacken_docs.format_str(before, BLACK_MODE) + assert after == before