Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 23 additions & 56 deletions .github/workflows/tox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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: |
Expand All @@ -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
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ __pycache__/
# Distribution / packaging
.Python
env/
/.venv
bin/
build/
develop-eggs/
Expand Down Expand Up @@ -57,3 +58,4 @@ src/doc8/_version.py
.idea/
.vscode/
junit.xml
uv.lock
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
~~~~~~~~~~~~~~

Expand Down
89 changes: 89 additions & 0 deletions src/doc8/_inline_markup.py
Original file line number Diff line number Diff line change
@@ -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
13 changes: 13 additions & 0 deletions src/doc8/checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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):
Expand Down
2 changes: 2 additions & 0 deletions src/doc8/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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",
Expand Down
12 changes: 11 additions & 1 deletion src/doc8/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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
Expand Down
Loading
Loading