diff --git a/.github/workflows/tox.yml b/.github/workflows/tox.yml index b531cbd..175bd67 100644 --- a/.github/workflows/tox.yml +++ b/.github/workflows/tox.yml @@ -23,32 +23,21 @@ env: PY_COLORS: 1 jobs: - prepare: - name: prepare - runs-on: ubuntu-24.04 - outputs: - matrix: ${{ steps.generate_matrix.outputs.matrix }} - steps: - - name: Determine matrix - id: generate_matrix - uses: coactions/dynamic-matrix@v4 - with: - min_python: "3.10" - max_python: "3.14" - default_python: "3.10" - other_names: | - lint - packaging - docs build: - name: ${{ matrix.name }} - runs-on: ${{ matrix.os || 'ubuntu-24.04' }} - needs: - - prepare - + name: ${{ matrix.tox_env }} + runs-on: ubuntu-24.04 strategy: fail-fast: false - matrix: ${{ fromJson(needs.prepare.outputs.matrix) }} + matrix: + include: + - {tox_env: py310, python_version: "3.10"} + - {tox_env: py311, python_version: "3.11"} + - {tox_env: py312, python_version: "3.12"} + - {tox_env: py313, python_version: "3.13"} + - {tox_env: py314, python_version: "3.14"} + - {tox_env: lint, python_version: "3.10"} + - {tox_env: packaging, python_version: "3.10"} + - {tox_env: docs, python_version: "3.10"} steps: - uses: actions/checkout@v4 @@ -58,18 +47,17 @@ jobs: - name: Set pre-commit cache uses: actions/cache@v4 - if: ${{ matrix.name == 'lint' }} + if: ${{ matrix.tox_env == 'lint' }} with: path: | ~/.cache/pre-commit - key: pre-commit-${{ matrix.name }}-${{ hashFiles('.pre-commit-config.yaml') }} + key: pre-commit-${{ matrix.tox_env }}-${{ hashFiles('.pre-commit-config.yaml') }} - - name: Set up Python ${{ matrix.python_version || '3.10' }} - if: "!contains(matrix.shell, 'wsl')" + - name: Set up Python ${{ matrix.python_version }} uses: actions/setup-python@v5 with: cache: pip - python-version: ${{ matrix.python_version || '3.10' }} + python-version: ${{ matrix.python_version }} - name: Install tox @@ -80,24 +68,12 @@ jobs: - name: Log installed dists run: python3 -m pip freeze --all - - run: ${{ matrix.command }} - - - run: ${{ matrix.command2 }} - if: ${{ matrix.command2 }} - - - run: ${{ matrix.command3 }} - if: ${{ matrix.command3 }} - - - run: ${{ matrix.command4 }} - if: ${{ matrix.command4 }} - - - run: ${{ matrix.command5 }} - if: ${{ matrix.command5 }} + - run: tox -e ${{ matrix.tox_env }} - name: Archive logs - uses: coactions/upload-artifact@v4 + uses: actions/upload-artifact@v4 with: - name: logs-${{ matrix.name }}.zip + name: logs-${{ matrix.tox_env }} include-hidden-files: true if-no-files-found: ignore path: | @@ -107,8 +83,8 @@ jobs: - name: Report failure if git reports dirty status run: | if [[ -n $(git status -s) ]]; then - # shellcheck disable=SC2016 echo -n '::error file=git-status::' + # shellcheck disable=SC2016 printf '### Failed as git reported modified and/or untracked files\n```\n%s\n```\n' "$(git status -s)" | tee -a "$GITHUB_STEP_SUMMARY" exit 99 fi @@ -132,27 +108,18 @@ jobs: - run: pip3 install 'coverage>=7.5.1' - - name: Merge logs into a single archive - uses: actions/upload-artifact/merge@v4 - with: - name: logs.zip - include-hidden-files: true - pattern: logs-*.zip - # artifacts like py312.zip and py312-macos do have overlapping files - separate-directories: true - - name: Download artifacts uses: actions/download-artifact@v4 continue-on-error: true # to allow rerunning this job with: - name: logs.zip + pattern: logs-* + merge-multiple: true path: . - name: Upload coverage data - uses: codecov/codecov-action@v5.4.3 + uses: codecov/codecov-action@v7.1.1 with: - name: ${{ matrix.name }} # verbose: true # optional (default = false) fail_ci_if_error: true use_oidc: ${{ !(github.event_name == 'pull_request' && github.event.pull_request.head.repo.fork) }} # cspell:ignore oidc diff --git a/.gitignore b/.gitignore index 28baac9..6f78cf5 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ __pycache__/ # Distribution / packaging .Python env/ +/.venv bin/ build/ develop-eggs/ @@ -57,3 +58,4 @@ src/doc8/_version.py .idea/ .vscode/ junit.xml +uv.lock diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a27605a..53f50e7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,7 +9,7 @@ repos: - id: trailing-whitespace - id: check-executables-have-shebangs - repo: https://github.com/asottile/pyupgrade - rev: v3.20.0 + rev: v3.21.2 hooks: - id: pyupgrade - repo: https://github.com/pappasam/toml-sort diff --git a/README.rst b/README.rst index 68313f5..41be42f 100644 --- a/README.rst +++ b/README.rst @@ -64,6 +64,7 @@ Usage - no tabulation for indentation - D003 - no carriage returns (use unix newlines) - D004 - no newline at end of file - D005 + - no inline literals inside emphasis - D006 positional arguments: path Path to scan for doc files (default: current @@ -94,6 +95,16 @@ Usage -v, --verbose run in verbose mode. --version show the version and exit. +D006 reports inline literals inside bold or italic text because +reStructuredText does not render both styles on the same text. +For example, keep only the inline literal:: + + ``event_id`` deduplication + +D006 flags the nested markup in this example:: + + **``event_id`` deduplication** + INI file usage ~~~~~~~~~~~~~~ diff --git a/src/doc8/_inline_markup.py b/src/doc8/_inline_markup.py new file mode 100644 index 0000000..587b491 --- /dev/null +++ b/src/doc8/_inline_markup.py @@ -0,0 +1,89 @@ +# MIT License +# +# Copyright (c) 2026 Adam Dangoor +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +from re import Match + +from docutils import nodes +from docutils.parsers.rst.states import Inliner +from docutils.utils import escape2null + + +class InlineMarkupInliner(Inliner): + """Look for inline literals left as text by the emphasis handlers.""" + + # Docutils interpolates these patterns from the concrete class namespace. + simplename = Inliner.simplename + emailc = Inliner.emailc + non_whitespace_after = Inliner.non_whitespace_after + non_whitespace_escape_before = Inliner.non_whitespace_escape_before + uric = Inliner.uric + uri_end = Inliner.uri_end + non_unescaped_whitespace_escape_before = ( + Inliner.non_unescaped_whitespace_escape_before + ) + + def __init__(self) -> None: + super().__init__() + self.dispatch = { + **self.dispatch, + # Docutils dispatches to unbound methods with the inliner as + # the first argument. types-docutils models these as bound. + "*": InlineMarkupInliner._emphasis, # type: ignore[dict-item] + "**": InlineMarkupInliner._emphasis, # type: ignore[dict-item] + } + self.lines: list[int] = [] + self._paragraph_lines = 0 + + def parse( + self, + text: str, + lineno: int, + memo, + parent: nodes.Element, + ): + self._paragraph_lines = text.count("\n") + return super().parse(text, lineno, memo, parent) + + def _emphasis(self, match: Match[str], lineno: int): + delimiter = match["start"] + handler = Inliner.strong if delimiter == "**" else Inliner.emphasis + before, inlines, remaining, messages = handler(self, match, lineno) + if inlines and isinstance(inlines[0], (nodes.strong, nodes.emphasis)): + raw = inlines[0].rawsource + body = raw[len(delimiter) : -len(delimiter)] + offset = self._literal_offset(text=body) + if offset is not None: + # Docutils passes the unconsumed suffix of the paragraph to + # each inline handler and keeps its original line number. + span_offset = self._paragraph_lines - match.string.count("\n") + self.lines.append(lineno + span_offset + before.count("\n") + offset) + return before, inlines, remaining, messages + + def _literal_offset(self, *, text: str) -> int | None: + escaped = escape2null(text) + for match in self.patterns.initial.finditer(escaped): + if match["start"] != "``" or self.quoted_start(match): + continue + end = self.patterns.literal.search(escaped[match.end("start") :]) + if end and end.start(1): + return escaped.count("\n", 0, match.start("start")) + return None diff --git a/src/doc8/checks.py b/src/doc8/checks.py index 2b6870f..0584c7c 100644 --- a/src/doc8/checks.py +++ b/src/doc8/checks.py @@ -81,6 +81,15 @@ def report_iter(self, parsed_file): yield (len(parsed_file.lines), "D005", "No newline at end of file") +class CheckNestedInlineLiteral(ContentCheck): + REPORTS = frozenset(["D006"]) + EXT_MATCHER = re.compile(r"\.rst$", re.IGNORECASE) + + def report_iter(self, parsed_file): + for line in parsed_file.nested_inline_literal_lines: + yield (line, "D006", "Move inline code outside emphasis") + + class CheckValidity(ContentCheck): REPORTS = frozenset(["D000"]) EXT_MATCHER = re.compile(r"(.*)[.]rst", re.IGNORECASE) @@ -121,6 +130,10 @@ class CheckValidity(ContentCheck): re.compile( r'^PEP number must be a number from 0 to 9999; "\d{1,4}#[^"]*" is invalid.', ), + re.compile( + r'^Error in "(?:admonition|attention|caution|danger|error|hint|important|note|tip|warning)" directive:\nunknown option: "collapsible"', + re.MULTILINE, + ), ] def __init__(self, cfg): diff --git a/src/doc8/main.py b/src/doc8/main.py index feb8cb6..b865a39 100644 --- a/src/doc8/main.py +++ b/src/doc8/main.py @@ -26,6 +26,7 @@ - no tabulation for indentation - D003 - no carriage returns (use unix newlines) - D004 - no newline at end of file - D005 + - no inline literals inside emphasis - D006 """ import argparse @@ -176,6 +177,7 @@ def fetch_checks(cfg): checks.CheckCarriageReturn(cfg), checks.CheckMaxLineLength(cfg), checks.CheckNewlineEndOfFile(cfg), + checks.CheckNestedInlineLiteral(cfg), ] mgr = extension.ExtensionManager( namespace="doc8.extension.check", diff --git a/src/doc8/parser.py b/src/doc8/parser.py index 8b34dba..cee6906 100644 --- a/src/doc8/parser.py +++ b/src/doc8/parser.py @@ -20,6 +20,8 @@ from docutils import frontend, utils from docutils import parsers as docutils_parser +from doc8._inline_markup import InlineMarkupInliner + class ParsedFile: FALLBACK_ENCODING = "utf-8" @@ -30,6 +32,7 @@ def __init__(self, filename, encoding=None, default_extension=""): self._raw_content = None self._encoding = encoding self._doc = None + self._nested_inline_literal_lines: tuple[int, ...] = () self._errors = None self._lines = None self._has_read = False @@ -53,7 +56,8 @@ def document(self): # parser is what sphinx and others use anyway so it's hopefully # mature). parser_cls = docutils_parser.get_parser_class("rst") - parser = parser_cls() + inliner = InlineMarkupInliner() + parser = parser_cls(inliner=inliner) defaults = { "halt_level": 5, "report_level": 5, @@ -71,9 +75,15 @@ def document(self): settings=opt.get_default_values(), ) parser.parse(self.contents, doc) + self._nested_inline_literal_lines = tuple(sorted(inliner.lines)) self._doc = doc return self._doc + @property + def nested_inline_literal_lines(self): + _ = self.document # Populate the line numbers during the shared parse. + return self._nested_inline_literal_lines + def _read(self): if self._has_read: return diff --git a/src/doc8/tests/test_checks.py b/src/doc8/tests/test_checks.py index 155c1ff..4171c98 100644 --- a/src/doc8/tests/test_checks.py +++ b/src/doc8/tests/test_checks.py @@ -183,3 +183,65 @@ def test_newline(self): check = checks.CheckNewlineEndOfFile({}) errors = list(check.report_iter(parsed_file)) self.assertEqual(expected_errors, len(errors)) + + +class TestValidity(unittest.TestCase): + def test_collapsible_admonition_ignored_in_sphinx_mode(self): + content = b".. note::\n :collapsible:\n\n Collapsible note.\n" + with tempfile.NamedTemporaryFile(suffix=".rst") as fh: + fh.write(content) + fh.flush() + parsed_file = parser.ParsedFile(fh.name) + check = checks.CheckValidity({"sphinx": True}) + errors = list(check.report_iter(parsed_file)) + self.assertEqual(0, len(errors)) + + def test_collapsible_admonition_flagged_without_sphinx_mode(self): + content = b".. note::\n :collapsible:\n\n Collapsible note.\n" + with tempfile.NamedTemporaryFile(suffix=".rst") as fh: + fh.write(content) + fh.flush() + parsed_file = parser.ParsedFile(fh.name) + check = checks.CheckValidity({"sphinx": False}) + errors = list(check.report_iter(parsed_file)) + self.assertEqual(1, len(errors)) + self.assertEqual("D000", errors[0][1]) + + +class TestNestedInlineLiteral(unittest.TestCase): + def test_nested_inline_literal(self): + cases = [ + (".. note:: **``event_id`` deduplication**\n", [1]), + ("*Use ``event_id`` for lookup.*\n", [1]), + ("``Standalone`` on the first line.\nThen **use ``event_id``**.\n", [2]), + ("First line.\n**Use\n``event_id`` here.**\n", [3]), + ("``ok``\n**``first``** and **``second``**\n", [2, 2]), + ("**``first`` and ``second``**\n", [1]), + ("**Use ``event\nid`` here.**\n", [1]), + ("**Documentation** and ``event_id``.\n", []), + ("**An unmatched ``marker**\n", []), + ("**A quoted pair '``' and ``.**\n", []), + ("**An escaped \\\x60\x60event_id``.**\n", []), + ("**``event_id`` with an unclosed span.\n", []), + (".. comment **``event_id``**\n", []), + (".. code-block:: rst\n\n **``event_id``**\n", []), + ("Example::\n\n **``event_id``**\n", []), + ("``**event_id**``\n", []), + (".. extension-directive::\n\n **``event_id``**\n", []), + ] + check = checks.CheckNestedInlineLiteral({}) + for text, expected_lines in cases: + with ( + self.subTest(text=text), + tempfile.NamedTemporaryFile(suffix=".rst") as fh, + ): + fh.write(text.encode("utf-8")) + fh.flush() + errors = list(check.report_iter(parser.ParsedFile(fh.name))) + self.assertEqual( + errors, + [ + (line, "D006", "Move inline code outside emphasis") + for line in expected_lines + ], + ) diff --git a/src/doc8/tests/test_main.py b/src/doc8/tests/test_main.py index 08e6b87..6b94e87 100644 --- a/src/doc8/tests/test_main.py +++ b/src/doc8/tests/test_main.py @@ -24,6 +24,7 @@ - doc8.checks.CheckCarriageReturn = 0 - doc8.checks.CheckIndentationNoTab = 0 - doc8.checks.CheckMaxLineLength = 0 + - doc8.checks.CheckNestedInlineLiteral = 0 - doc8.checks.CheckNewlineEndOfFile = 1 - doc8.checks.CheckTrailingWhitespace = 1 - doc8.checks.CheckValidity = 0 @@ -47,6 +48,7 @@ Running check 'doc8.checks.CheckMaxLineLength' Running check 'doc8.checks.CheckNewlineEndOfFile' - {path}/invalid.rst:1: D005 No newline at end of file + Running check 'doc8.checks.CheckNestedInlineLiteral' ======== Total files scanned = 1 Total files ignored = 0 @@ -55,6 +57,7 @@ - doc8.checks.CheckCarriageReturn = 0 - doc8.checks.CheckIndentationNoTab = 0 - doc8.checks.CheckMaxLineLength = 0 + - doc8.checks.CheckNestedInlineLiteral = 0 - doc8.checks.CheckNewlineEndOfFile = 1 - doc8.checks.CheckTrailingWhitespace = 1 - doc8.checks.CheckValidity = 0 @@ -71,6 +74,7 @@ - doc8.checks.CheckCarriageReturn = 0 - doc8.checks.CheckIndentationNoTab = 0 - doc8.checks.CheckMaxLineLength = 0 + - doc8.checks.CheckNestedInlineLiteral = 0 - doc8.checks.CheckNewlineEndOfFile = 1 - doc8.checks.CheckTrailingWhitespace = 1 - doc8.checks.CheckValidity = 0""" @@ -214,6 +218,26 @@ def test_doc8__verbose__verbose_overridden(self): self.assertEqual(err.getvalue(), "") self.assertEqual(result.total_errors, 2) + def test_doc8__nested_inline_literal_in_rst_only(self): + with TmpFs() as tmpfs: + for filename in ("example.RST", "example.txt"): + tmpfs.create_file(filename, "**``event_id`` deduplication**\n") + + options = {"paths": [tmpfs.path], "extension": [".RST", ".txt"]} + result = doc8(**options) + self.assertEqual( + [error[1:] for error in result.errors], + [ + ( + f"{tmpfs.path}/example.RST", + 1, + "D006", + "Move inline code outside emphasis", + ), + ], + ) + self.assertEqual(doc8(**options, ignore={"D006"}).errors, []) + class TestArguments(unittest.TestCase): """Test that arguments are parsed correctly"""