adamchainz / blacken-docs

Run `black` on python code blocks in documentation files
MIT License
646 stars 43 forks source link

Improve the failure mode on an empty code-block directive #368

Closed sirosen closed 1 month ago

sirosen commented 2 months ago

Python Version

3.11.9

Package Version

1.18.0

Description

While refactoring some docs, I accidentally separated a .. code-block:: python directive from the relevant indented code block. So my docs had the form:

Title
=====

.. code-block:: python

Subsection
----------

The failure mode I got was a crash, which is, IMO, the correct result but the nature of the crash was not informative. Trace (invoked via pre-commit):


Traceback (most recent call last):
  File "/home/sirosen/.cache/pre-commit/repojdmsuxmq/py_env-python3.11/bin/blacken-docs", line 8, in <module>
    sys.exit(main())
             ^^^^^^
  File "/home/sirosen/.cache/pre-commit/repojdmsuxmq/py_env-python3.11/lib/python3.11/site-packages/blacken_docs/__init__.py", line 349, in main
    retv |= format_file(
            ^^^^^^^^^^^^
  File "/home/sirosen/.cache/pre-commit/repojdmsuxmq/py_env-python3.11/lib/python3.11/site-packages/blacken_docs/__init__.py", line 287, in format_file
    new_contents, errors = format_str(
                           ^^^^^^^^^^^
  File "/home/sirosen/.cache/pre-commit/repojdmsuxmq/py_env-python3.11/lib/python3.11/site-packages/blacken_docs/__init__.py", line 265, in format_str
    src = RST_RE.sub(_rst_match, src)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/sirosen/.cache/pre-commit/repojdmsuxmq/py_env-python3.11/lib/python3.11/site-packages/blacken_docs/__init__.py", line 162, in _rst_match
    min_indent = min(INDENT_RE.findall(match["code"]))
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: min() arg is an empty sequence

I think that when there is no match for a code block, it would be nice to bomb out with an explicit ValueError which contains the filename in the message. e.g., ValueError: docs/foo.rst has a code-block with no content

adamchainz commented 2 months ago

Yeah, it would be good to avoid this. I think it would be better to silently ignore the broken syntax. Your actual docs-building tool, or an rST linter, are better suited for detecting and reporting on such errors.

Would you like to work on a PR?

sirosen commented 2 months ago

Would you like to work on a PR?

Yes, I'd love to!

I'm not able to today, but maybe tomorrow or later this week