Skip to content

Commit

Permalink
reStructuredText: gracefully ignore empty code blocks (#369)
Browse files Browse the repository at this point in the history
Co-authored-by: Adam Johnson <me@adamj.eu>
  • Loading branch information
sirosen and adamchainz authored Oct 7, 2024
1 parent 1583d9e commit 6849124
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
Changelog
=========

* reStructuredText: Gracefully ignore empty code blocks.

Thanks to Stephen Rosen in `PR #368 <https://github.com/adamchainz/blacken-docs/issues/368>`__.

* Drop Python 3.8 support.

* Support Python 3.13.
Expand Down
4 changes: 4 additions & 0 deletions src/blacken_docs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}'
Expand Down
27 changes: 27 additions & 0 deletions tests/test_blacken_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
"""\
Expand All @@ -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(
"""
Expand Down Expand Up @@ -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

0 comments on commit 6849124

Please sign in to comment.