Welcome to rstcheck-core’s documentation!

General

Maintenance - intended License Semantic Versioning - 2.0.0

Read the Docs - Build Status (latest)

CI

Test status Documentation status QA status

PyPI

PyPI - Package latest release PyPI - Supported Python Versions PyPI - Supported Implementations

PyPI - Format PyPI - Monthly downloads

Github

Github - Latest Release GitHub - Last Commit

Github - Stars Github - Forks Github - Contributors Github - Watchers

This a the documentation of rstcheck-core. The core library behind the CLI application rstcheck for checking the syntax of reStructuredText and code blocks nested within it.

Installation

This part of the documentation covers how to install the package. It is recommended to install the package in a virtual environment.

Create virtual environment

There are several packages/modules for creating python virtual environments. Here is a manual by the PyPA.

Installation from PyPI

You can simply install the package from PyPI:

$ pip install rstcheck-core

Extras

rstcheck-core has extras which can be installed to activate optional functionality:

  • sphinx - To activate support for rst documents using the sphinx builder.

  • toml - To activate support for TOML files as configuration files.

To install an extra simply add it in brackets like so:

$ pip install rstcheck-core[sphinx,toml]

Installation from source

You can install rstcheck-core directly from a Git repository clone. This can be done either by cloning the repository and installing from the local clone:

$ git clone https://github.com/rstcheck/rstcheck-core
$ cd rstcheck-core
$ pip install .

Or installing directly via git:

$ pip install git+https://github.com/rstcheck/rstcheck-core

You can also download the current version as tar.gz or zip file, extract it and install it with pip like above.

Usage

rstcheck-core is a library and the heart of rstcheck. Here you can find how to use it.

Configuration

rstcheck-core’s config system knows three sources:

  • Inline comments (for config and flow control instructions)

  • CLI options

  • Config files (INI and TOML)

Order of application

The config sources apply according to a set of rules:

  1. Flow control instructions from inline comments:

    • always apply regardless of other config.

    • are expressive and say for themselves what they apply to.

  2. Config from inline comments:

    • always apply regardless of other config.

    • always apply for the whole file regardless where they are placed.

    • is added to the remaining config and does not overwrite it.

  3. CLI options always overwrite config coming from a file.

  4. File config has the lowest priority.

Configuration sources

Now let’s take a deeper look at the different sources of config.

Inline comments

Inline comments are simply rst comments starting with rstcheck:. There are two types of inline comments:

  • Simple inline config e.g. ignore-languages=python which follows the syntax of key=value.

  • Flow control instructions e.g. ignore-next-code-block which follows the syntax of words-divided-by-dashes.

Here is an example with both of them:

Example
=======

.. rstcheck: ignore-next-code-block
.. code-block:: python

    print("Hello World")

.. rstcheck: ignore-languages=python
Configuration files

rstcheck-core has an automatic config file detection mechanic. This mechanic includes the following config files sorted by priority:

  1. .rstcheck.cfg

  2. pyproject.toml

  3. setup.cfg

When a directory is searched for a config file, the first found config section is taken and the search is not aborted on the first file found. This means that if you for example have a pyproject.toml file without a matching config section and an setup.cfg file with a matching section, the section from setup.cfg would be used. pyproject.toml would be searched first, but nothing would be found and so the search would continue.

For each rst source file that is linted, its parent directory is searched for a config file. If the parent directory has no config file with a matching config section the parent’s parent directory is searched next. This continues up the directory tree until the root directory. If no config file is found, the default values for each setting apply.

This whole mechanic is deactivated, when a config file or directory is explicitly set. See the Configuration file section for more information on setting a config file/directory.

rstcheck-core supports two types of config formats: INI and TOML. They are written pretty similar, but have some differences. The two following sections explain both formats.

Files ending on .toml are parsed as TOML files. Every other file is parsed as an INI file.

If .rstcheck.cfg does not contain a valid section a warning is printed.

INI format

In INI format all config related to rstcheck-core must go into a [rstcheck] section.

The default INI format applies: key = value. Lists are comma-separated strings, which can be multiline. Whitespace before and after a key or value is ignored. Trailing commas are optional.

Here is an example:

[rstcheck]
report_level=WARNING
ignore_directives =
    one,
    two,
    three,
ignore_roles=src, RFC
ignore_substitutions=
    image_link
ignore_languages=
    python,
    cpp
ignore_messages=(Document or section may not begin with a transition\.$)
TOML format

Note

TOML format is only supported when the python library tomli is importable if the used python version is lower than 3.11. See the Installation section for more information.

In TOML format all config related to rstcheck-core must go into the [tool.rstcheck] dictionary. This is due to the python convention for the pyproject.toml file, which rstcheck-core uses for all TOML files.

The official TOML syntax applies here, so strings are strings and lists are lists for example.

Here is an example:

[tool.rstcheck]
report_level = "WARNING"
ignore_directives = [
    "one",
    "two",
    "three",
]
ignore_roles = ["src", "RFC"]
ignore_substitutions = [
    "image_link"
]
ignore_languages = [
    "python",
    "cpp"
]
ignore_messages = "(Document or section may not begin with a transition\.$)"

Configuration options

Now it’s time for all the available settings you can set.

Configuration file

Supported sources:

  • CLI (--config PATH )

With the --config CLI option you can set a config file or directory. The path may be relative or absolute.

If the passed path does not exist the runner exits with an error, which is logged.

If the path is a literal NONE, no file is loaded or directory searched, this includes the automatic config file detection mechanic.

When the path points to a file, this concrete file is read and searched for a matching config section. If no section is found a warning is logged and no file config is used.

When the path is a directory, this directory is search for a config file, like described in the earlier Configuration files section, except that only this directory is search and not the directory tree.

Recursive resolution

Supported sources:

  • CLI (--recursive or -r)

By default only files passed to the CLI runner are checked and directories are ignored. When this config is set, passed directories are searched recursively for rst source files.

Report level

Supported sources:

  • CLI (--report-level LEVEL)

  • File (key: report_level, value: LEVEL)

The level at which linting issues should be printed. The following levels are supported:

  • INFO (default)

  • WARNING

  • ERROR

  • SEVERE

  • NONE

This currently only applies to issues with rst source. Issues in code blocks are on ERROR level and always printed, even if the level is set to SEVERE or NONE.

The level can be set case insensitive.

Logging level

Supported sources:

  • CLI (--log-level LEVEL)

The level at which additional information besides linting issues should be printed. The following levels are supported:

  • DEBUG

  • INFO

  • WARNING (default)

  • ERROR

  • CRITICAL

The level can be set case insensitive.

Ignore directives

Supported sources:

  • Inline comments (key: ignore-directives, value: list of directives)

  • CLI (--ignore-directives D1,D2,...)

  • File (key: ignore_directives, value: list of directives)

A list of directives to ignore while checking rst source.

Ignore roles

Supported sources:

  • Inline comments (key: ignore-roles, value: list of roles)

  • CLI (--ignore-roles R1,R2,...)

  • File (key: ignore_roles, value: list of roles)

A list of roles to ignore while checking rst source.

Ignore substitutions

Supported sources:

  • Inline comments (key: ignore-substitutions, value: list of substitutions)

  • CLI (--ignore-substitutions S1,S2,...)

  • File (key: ignore_substitutions, value: list of substitutions)

A list of substitutions to ignore while checking rst source.

Ignore specific code-block languages

Supported sources:

  • Inline comments (key: ignore-languages, value: list of languages)

  • CLI (--ignore-languages L1,L2,...)

  • File (key: ignore_languages, value: list of languages)

A list of languages to ignore for code blocks in rst source. Unsupported languages are ignored automatically.

Supported languages are:

  • Bash

  • Doctest

  • C (C99)

  • C++ (C++11)

  • JSON

  • XML

  • Python

  • reStructuredText

Ignore specific error messages

Supported sources:

  • CLI (--ignore-messages REGEX_STRING)

  • File (key: ignore_messages, value: regular expression string)

A list of linting issue messages to ignore while checking rst source and code blocks.

Note

In TOML format a list of strings is also valid. The list’s entries will be concatenated with the OR operator “|” between each entry.

Control Flow instructions

There are also control flow instructions which are only available as inline comments. They change the flow of checking the rst source, hence the name.

Skipping code blocks

With the ignore-next-code-block flow control instruction you can skip single code blocks. This way you don’t have to use the heavy tools like ignoring a whole language or directive.

The instruction must be placed in the line directly above the code block directive like so:

.. rstcheck: ignore-next-code-block
.. code-block:: python

    print("Hello world")

Examples with explanation

These examples are cases to show concepts of configuration in rstcheck-core. They don’t always follow best practices.

Only inline comments
Example
=======

.. rstcheck: ignore-next-code-block
.. code-block:: python

    print("Here is an error."

.. rstcheck: ignore-languages=python

In this example the code-block would be ignored/skipped due to the flow control instruction. But the code-block’s language is python which is on the ignore list for languages, because of the config at the bottom. This means if you remove the flow control instruction, the code-block would still be skipped and the error inside would ignored.

Library

Documentation for the open API of the library can be found in the API section.

Entry Points

This library has two main entry points you can use:

rstcheck_core.runner.RstcheckMainRunner class

The RstcheckMainRunner class the is main entry point. It manages the configuration state, runs the check on the files, caches the found linting issues and prints them.

rstcheck_core.checker.check_file() function

The check_file function is a step deeper. It checks a single file and returns a list of the found linting issues. This would be the entry point if you don’t need the additional management capabilities of the RstcheckMainRunner class.

Logging

rstcheck-core uses the standard library’s logging module for its logging functionality.

Each python module has its own logger named after the __file__ variable’s value.

Following the Official HOWTO logging is deactivated by default, but can be activated, if you as a developer provide a logging configuration.

Workflows

Here is the documentation about different workflows for rstcheck-core.

Development

rstcheck-core uses Semantic Versioning.

rstcheck-core uses main as its single development branch. Therefore releases are made from this branch. Only the current release is supported and bugfixes are released with a patch release for the current minor release.

Tooling

For development the following tools are used:

  • poetry for dependency management, package metadata, building and publishing.

  • tox for automated and isolated testing.

  • pre-commit for automated QA checks via different linters and formatters.

Set up Local Development Environment

The setup of a local development environment is pretty easy. The only tool you need is the poetry. You can install it via the recommended way, which installs it globally on your system or you can install it via pip in a self-created virtualenv (virtualenv manual).

With poetry set up and ready we can create our development environment in just one step:

$ poetry install

This will install rstcheck-core along its main and development dependencies.

Working with the Local Development Environment

Dependency management and more with poetry

is used for dependency management, building and publishing rstcheck-core.

Testing with tox

To run all available tests and check simply run:

$ tox

This will run:

  • formatters and linters via pre-commit.

  • the full test suite with pytest.

  • a test coverage report.

  • tests for the documentation.

Different environment lists are available and can be selected with tox -n <ENVLIST>:

  • test: run full test suite with pytest and report coverage.

  • py3.7 - py3.10 run full test suite with specific python version and report coverage.

  • docs: run all documentation tests.

Linting and formatting pre-commit

can be used directly from within the development environment or you can use tox to run it pre-configured.

There are 3 available tox envs with all use the same virtualenv:

  • pre-commit: For running any pre-commit command like tox -e pre-commit -- autoupdate --freeze.

  • pre-commit-run: For running all hooks against the code base. A single hook’s id can be passed as argument to run this hook only like tox -e pre-commit-run -- black.

  • pre-commit-install: For installing pre-commit hooks as git hooks, to automatically run them before every commit.

IDE integration

The development environment has flakeheaven (a flake8 wrapper), pylint and mypy installed to allow IDEs to use them for inline error messages. Their config is in pyproject.toml. To run them actively use pre-commit and/or tox.

Releases

Release workflow

When enough changes and additions or time important fixes have accumulated on the main branch its time for a new release. The exact time is subject to the judgment of the maintainer(s).

Note

Before starting the process of creating a new release make sure that all CI pipelines are green for the current commit.

  1. Check if the CHANGELOG.md is up-to-date and all changes are noted.

  2. Run prep_release.py script to bump version, finalize CHANGELOG.md, commit the changes and create a new git tag:

    $ python3 prep_release.py <TYPE>
    

    For the increase type there are three options:

    • patch / bugfix: for changes that do not add new functionality and are backwards compatible

    • minor / feature: for changes that do add new functionality and are backwards compatible

    • major / breaking: for changes that are not backwards compatible

  3. Build the sdist and wheel:

    $ poetry build
    
  4. Publish package:

    $ poetry publish
    
  5. Push the commit and tag to github:

    $ git push --follow-tags
    

API

This part of the documentation covers the open API of rstcheck-core and is auto generated by sphinx-apidoc via sphinxcontrib-apidoc.

rst-source links (top right) do not work here, as auto generated api documentation files are discarded after build.

rstcheck_core package

Submodules

rstcheck_core.checker module

rstcheck_core.checker.check_file(source_file, rstcheck_config, overwrite_with_file_config=True)[source]

Check the given file for issues.

On every call docutils’ caches for roles and directives are cleared by reloading their modules.

Parameters:
  • source_file (Path) – Path to file to check

  • rstcheck_config (RstcheckConfig) – Main configuration of the application

  • overwrite_with_file_config (bool) – If the loaded file config should overwrite the rstcheck_config; defaults to True

Return type:

List[LintError]

Returns:

A list of found issues

rstcheck_core.checker.check_source(source, source_file=None, ignores=None, report_level=ReportLevel.INFO, warn_unknown_settings=False)[source]

Check the given rst source for issues.

Parameters:
Return type:

Generator[LintError, None, None]

Returns:

None

Yield:

Found issues

class rstcheck_core.checker.CodeBlockChecker(source_origin, ignores=None, report_level=ReportLevel.INFO, warn_unknown_settings=False)[source]

Bases: object

Checker for code blockes with different languages.

Inititalize CodeBlockChecker.

Parameters:
language_is_supported(language)[source]

Check if given language can be checked.

Parameters:

language (str) – Language to check

Return type:

bool

Returns:

If langauge can be checked

create_checker(source_code, language)[source]

Create a checker function for the given source and language.

Parameters:
  • source – Source code to check

  • language (str) – Language of the source code

  • source_code (str) –

Return type:

Callable[..., Generator[LintError, None, None]]

Returns:

Checker function

check(source_code, language)[source]

Call the appropiate checker function for the given langauge to check given source.

Parameters:
  • source – Source code to check

  • language (str) – Language of the source code

  • source_code (str) –

Return type:

Generator[LintError, None, None]

Returns:

None if language is not supported

Yield:

Found issues

check_python(source_code)[source]

Check python source for syntax errors.

Parameters:
  • source – Python source code to check

  • source_code (str) –

Return type:

Generator[LintError, None, None]

Returns:

None

Yield:

Found issues

check_json(source_code)[source]

Check JSON source for syntax errors.

Parameters:
  • source – JSON source code to check

  • source_code (str) –

Return type:

Generator[LintError, None, None]

Returns:

None

Yield:

Found issues

check_xml(source_code)[source]

Check XML source for syntax errors.

Parameters:
  • source – XML source code to check

  • source_code (str) –

Return type:

Generator[LintError, None, None]

Returns:

None

Yield:

Found issues

check_rst(source_code)[source]

Check nested rst source for syntax errors.

Parameters:
  • source – rst source code to check

  • source_code (str) –

Return type:

Generator[LintError, None, None]

Returns:

None

Yield:

Found issues

check_doctest(source_code)[source]

Check doctest source for syntax errors.

This does not run the test as that would be unsafe. Nor does this check the Python syntax in the doctest. That could be purposely incorrect for testing purposes.

Parameters:
  • source – XML source code to check

  • source_code (str) –

Return type:

Generator[LintError, None, None]

Returns:

None

Yield:

Found issues

check_bash(source_code)[source]

Check bash source for syntax errors.

Parameters:
  • source – bash source code to check

  • source_code (str) –

Return type:

Generator[LintError, None, None]

Returns:

None

Yield:

Found issues

check_c(source_code)[source]

Check C source for syntax errors.

Parameters:
  • source – C source code to check

  • source_code (str) –

Return type:

Generator[LintError, None, None]

Returns:

None

Yield:

Found issues

check_cpp(source_code)[source]

Check C++ source for syntax errors.

Parameters:
  • source – C++ source code to check

  • source_code (str) –

Return type:

Generator[LintError, None, None]

Returns:

None

Yield:

Found issues

rstcheck_core.config module

rstcheck_core.config.CONFIG_FILES = ['.rstcheck.cfg', 'setup.cfg']

Supported default config files.

class rstcheck_core.config.ReportLevel(value)[source]

Bases: Enum

Report levels supported by docutils.

INFO = 1
WARNING = 2
ERROR = 3
SEVERE = 4
NONE = 5
rstcheck_core.config.ReportLevelMap = {'error': 3, 'info': 1, 'none': 5, 'severe': 4, 'warning': 2}

Map docutils report levels in text form to numbers.

rstcheck_core.config.DEFAULT_REPORT_LEVEL = ReportLevel.INFO

Default report level.

class rstcheck_core.config.RstcheckConfigFile(**data)[source]

Bases: BaseModel

Rstcheck config file.

Raises:
Parameters:

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

report_level: Optional[ReportLevel]
ignore_directives: Optional[List[str]]
ignore_roles: Optional[List[str]]
ignore_substitutions: Optional[List[str]]
ignore_languages: Optional[List[str]]
ignore_messages: Optional[Pattern]
classmethod valid_report_level(value)[source]

Validate the report_level setting.

Parameters:

value (Any) – Value to validate

Raises:

ValueError – If value is not a valid docutils report level

Return type:

Optional[ReportLevel]

Returns:

Instance of ReportLevel or None if emptry string.

classmethod split_str(value)[source]

Validate and parse the following ignore_* settings.

  • ignore_directives

  • ignore_roles

  • ignore_substitutions

  • ignore_languages

Comma separated strings are split into a list.

Parameters:

value (Any) – Value to validate

Raises:

ValueError – If not a str or list of str

Return type:

Optional[List[str]]

Returns:

List of things to ignore in the respective category

classmethod join_regex_str(value)[source]

Validate and concatenate the ignore_messages setting to a RegEx string.

If a list ist given, the entries are concatenated with “|” to create an or RegEx.

Parameters:

value (Any) – Value to validate

Raises:

ValueError – If not a str or list of str

Return type:

Union[str, Pattern[str], None]

Returns:

A RegEx string with messages to ignore or typing.Pattern if it is one already

class rstcheck_core.config.RstcheckConfig(**data)[source]

Bases: RstcheckConfigFile

Rstcheck config.

Raises:
Parameters:

Create a new model by parsing and validating input data from keyword arguments.

Raises ValidationError if the input data cannot be parsed to form a valid model.

config_path: Optional[Path]
recursive: Optional[bool]
warn_unknown_settings: Optional[bool]
rstcheck_core.config.load_config_file(file_path, *, log_missing_section_as_warning=True, warn_unknown_settings=False)[source]

Load, parse and validate rstcheck config from a file.

Caution

If a TOML file is passed this function need tomli installed for python versions before 3.11! Use toml extra or install manually.

Parameters:
  • file_path (Path) – File to load config from

  • log_missing_section_as_warning (bool) – If a missing config section should be logged at WARNING (True) or INFO (False) level; defaults to True

  • warn_unknown_settings (bool) – If a warning should be logged for unknown settings in config file; defaults to False

Raises:

FileNotFoundError – If the file is not found

Return type:

Optional[RstcheckConfigFile]

Returns:

instance of RstcheckConfigFile or None on missing config section or NONE is passed as the config path.

rstcheck_core.config.load_config_file_from_dir(dir_path, *, log_missing_section_as_warning=False, warn_unknown_settings=False)[source]

Search, load, parse and validate rstcheck config from a directory.

Searches files from CONFIG_FILES in the directory. If a file is found, try to load the config from it. If is has no config, search further.

Parameters:
  • dir_path (Path) – Directory to search

  • log_missing_section_as_warning (bool) – If a missing config section in a config file should be logged at WARNING (True) or INFO (False) level; defaults to False

  • warn_unknown_settings (bool) – If a warning should be logged for unknown settings in config file; defaults to False

Return type:

Optional[RstcheckConfigFile]

Returns:

instance of RstcheckConfigFile or None if no file is found or no file has a rstcheck section or NONE is passed as the config path.

rstcheck_core.config.load_config_file_from_dir_tree(dir_path, *, log_missing_section_as_warning=False, warn_unknown_settings=False)[source]

Search, load, parse and validate rstcheck config from a directory tree.

Searches files from CONFIG_FILES in the directory. If a file is found, try to load the config from it. If is has no config, search further. If no config is found in the directory search its parents one by one.

Parameters:
  • dir_path (Path) – Directory to search

  • log_missing_section_as_warning (bool) – If a missing config section in a config file should be logged at WARNING (True) or INFO (False) level; defaults to False

  • warn_unknown_settings (bool) – If a warning should be logged for unknown settings in config file; defaults to False

Return type:

Optional[RstcheckConfigFile]

Returns:

instance of RstcheckConfigFile or None if no file is found or no file has a rstcheck section or NONE is passed as the config path.

rstcheck_core.config.load_config_file_from_path(path, *, search_dir_tree=False, log_missing_section_as_warning_for_file=True, log_missing_section_as_warning_for_dir=False, warn_unknown_settings=False)[source]

Analyse the path and call the correct config file loader.

Parameters:
  • path (Path) – Path to load config file from; can be a file or directory

  • search_dir_tree (bool) – If the directory tree should be searched; only applies if path is a directory; defaults to False

  • log_missing_section_as_warning_for_file (bool) – If a missing config section in a config file should be logged at WARNING (True) or INFO (False) level when the given path is a file; defaults to True

  • log_missing_section_as_warning_for_dir (bool) – If a missing config section in a config file should be logged at WARNING (True) or INFO (False) level when the given file is a direcotry; defaults to False

  • warn_unknown_settings (bool) – If a warning should be logged for unknown settings in config file; defaults to False

Raises:

FileNotFoundError – When the passed path is not found.

Return type:

Optional[RstcheckConfigFile]

Returns:

instance of RstcheckConfigFile or None if no file is found or no file has a rstcheck section or NONE is passed as the config path.

rstcheck_core.config.merge_configs(config_base, config_add, *, config_add_is_dominant=True)[source]

Merge two configs into a new one.

Parameters:
Return type:

RstcheckConfig

Returns:

New merged config

rstcheck_core.inline_config module

rstcheck_core.inline_config.get_inline_config_from_source(source, source_origin, warn_unknown_settings=False)[source]

Get rstcheck inline configs from source.

Unknown configs are ignored.

Parameters:
  • source (str) – Source to get config from

  • source_origin (Union[Path, Literal['<string>'], Literal['<stdin>']]) – Origin of the source with the inline ignore comments

  • warn_unknown_settings (bool) – If a warning should be logged on unknown settings; defaults to False

Return type:

List[InlineConfig]

Returns:

A list of inline configs

rstcheck_core.inline_config.find_ignored_directives(source, source_origin, warn_unknown_settings=False)[source]

Search the rst source for rstcheck inline ignore-directives comments.

Directives are ignored via comment.

For example, to ignore directive1, directive2, and directive3:

>>> list(find_ignored_directives('''
... Example
... =======
...
... .. rstcheck: ignore-directives=directive1,directive3
...
... .. rstcheck: ignore-directives=directive2
... ''', "<string>"))
['directive1', 'directive3', 'directive2']
Parameters:
  • source (str) – Rst source code

  • source_origin (Union[Path, Literal['<string>'], Literal['<stdin>']]) – Origin of the source with the inline ignore comments

  • warn_unknown_settings (bool) –

Return type:

Generator[str, None, None]

Returns:

None

Yield:

Found directives to ignore

rstcheck_core.inline_config.find_ignored_roles(source, source_origin, warn_unknown_settings=False)[source]

Search the rst source for rstcheck inline ignore-roles comments.

Roles are ignored via comment.

For example, to ignore role1, role2, and role3:

>>> list(find_ignored_roles('''
... Example
... =======
...
... .. rstcheck: ignore-roles=role1,role3
...
... .. rstcheck: ignore-roles=role2
... ''', "<string>"))
['role1', 'role3', 'role2']
Parameters:
  • source (str) – Rst source code

  • source_origin (Union[Path, Literal['<string>'], Literal['<stdin>']]) – Origin of the source with the inline ignore comments

  • warn_unknown_settings (bool) –

Return type:

Generator[str, None, None]

Returns:

None

Yield:

Found roles to ignore

rstcheck_core.inline_config.find_ignored_substitutions(source, source_origin, warn_unknown_settings=False)[source]

Search the rst source for rstcheck inline ignore-substitutions comments.

Substitutions are ignored via comment.

For example, to ignore substitution1, substitution2, and substitution3:

>>> list(find_ignored_substitutions('''
... Example
... =======
...
... .. rstcheck: ignore-substitutions=substitution1,substitution3
...
... .. rstcheck: ignore-substitutions=substitution2
... ''', "<string>"))
['substitution1', 'substitution3', 'substitution2']
Parameters:
  • source (str) – Rst source code

  • source_origin (Union[Path, Literal['<string>'], Literal['<stdin>']]) – Origin of the source with the inline ignore comments

  • warn_unknown_settings (bool) –

Return type:

Generator[str, None, None]

Returns:

None

Yield:

Found substitutions to ignore

rstcheck_core.inline_config.find_ignored_languages(source, source_origin, warn_unknown_settings=False)[source]

Search the rst source for rstcheck inline ignore-languages comments.

Languages are ignored via comment.

For example, to ignore C++, JSON, and Python:

>>> list(find_ignored_languages('''
... Example
... =======
...
... .. rstcheck: ignore-languages=cpp,json
...
... .. rstcheck: ignore-languages=python
... ''', "<string>"))
['cpp', 'json', 'python']
Parameters:
  • source (str) – Rst source code

  • source_origin (Union[Path, Literal['<string>'], Literal['<stdin>']]) – Origin of the source with the inline ignore comments

  • warn_unknown_settings (bool) –

Return type:

Generator[str, None, None]

Returns:

None

Yield:

Found languages to ignore

rstcheck_core.inline_config.get_inline_flow_control_from_source(source, source_origin, warn_unknown_settings=False)[source]

Get rstcheck inline flow control from source.

Unknown flow controls are ignored.

Parameters:
  • source (str) – Source to get config from

  • source_origin (Union[Path, Literal['<string>'], Literal['<stdin>']]) – Origin of the source with the inline flow control

  • warn_unknown_settings (bool) – If a warning should be logged on unknown settings; defaults to False

Return type:

List[InlineFlowControl]

Returns:

A list of inline flow controls

rstcheck_core.inline_config.find_code_block_ignore_lines(source, source_origin, warn_unknown_settings=False)[source]

Get lines of ignore-next-code-block flow control comments.

Parameters:
  • source (str) – Source to get config from

  • source_origin (Union[Path, Literal['<string>'], Literal['<stdin>']]) – Origin of the source with the inline ignore comments

  • warn_unknown_settings (bool) – If a warning should be logged on unknown settings; defaults to False

Return type:

Generator[int, None, None]

Returns:

None

Yield:

Single values for the target_config

rstcheck_core.runner module

class rstcheck_core.runner.RstcheckMainRunner(check_paths, rstcheck_config, overwrite_config=True)[source]

Bases: object

Main runner of rstcheck_core.

Initialize the RstcheckMainRunner with a base config.

Parameters:
  • check_paths (List[Path]) – Files to check.

  • rstcheck_config (RstcheckConfig) – Base configuration config from e.g. the CLI.

  • overwrite_config (bool) – If file config overwrites current config; defaults to True

property files_to_check: List[Path]

List of files to check.

This list is updated via the RstcheckMainRunner.update_file_list() method.

property nonexisting_paths: List[Path]

List of paths which do not exist.

This list is updated via the RstcheckMainRunner.update_file_list() method.

load_config_file(config_path, warn_unknown_settings=False)[source]

Load config from file and merge with current config.

If the loaded file config overwrites the current config depends on the self.overwrite_config attribute set on initialization.

Parameters:
  • config_path (Path) – Path to config file; can be directory or file

  • warn_unknown_settings (bool) – If a warning should be logged for unknown settings in config file; defaults to False

Return type:

None

update_file_list()[source]

Update file path list with paths specified on initialization.

Uses paths from RstcheckMainRunner.check_paths, resolves all file paths and saves them in RstcheckMainRunner.files_to_check.

If a given path does not exist, it is filtered out and saved in RstcheckMainRunner.files_to_check.

Clear the current file list. Then get the file and directory paths specified with self.check_paths attribute set on initialization and search them for rst files to check. Add those files to the file list.

Return type:

None

check()[source]

Check all files in the file list and save the errors.

Multiple files are run in parallel.

A new call overwrite the old cached errors.

Return type:

None

print_result(output_file=None)[source]

Print all cached error messages and return exit code.

Parameters:

output_file (Optional[TextIO]) – file to print to; defaults to sys.stderr (if None)

Return type:

int

Returns:

exit code 0 if no error is printed; 1 if any error is printed

run()[source]

Run checks, print error messages and return the result.

Return type:

int

Returns:

exit code 0 if no error is printed; 1 if any error is printed

rstcheck_core.types module

rstcheck_core.types.SourceFileOrString

Path to source file or if it is a string then ‘<string>’ or ‘<stdin>’.

alias of Union[Path, Literal[‘<string>’], Literal[‘<stdin>’]]

class rstcheck_core.types.LintError(*args, **kwargs)[source]

Bases: dict

Dict with information about an linting error.

source_origin: Union[Path, Literal['<string>'], Literal['<stdin>']]
line_number: int
message: str
rstcheck_core.types.YieldedLintError

Yielded version of type LintError.

alias of Generator[LintError, None, None]

class rstcheck_core.types.IgnoreDict(*args, **kwargs)[source]

Bases: dict

Dict with ignore information.

messages: Optional[Pattern]
languages: List[str]
directives: List[str]
roles: List[str]
substitutions: List[str]
rstcheck_core.types.construct_ignore_dict(messages=None, languages=None, directives=None, roles=None, substitutions=None)[source]

Create an IgnoreDict with passed values or defaults.

Parameters:
Return type:

IgnoreDict

Returns:

IgnoreDict with passed values or defaults

rstcheck_core.types.CheckerRunFunction

Function to run checks.

Returned by rstcheck_core.checker.CodeBlockChecker.create_checker().

alias of Callable[[…], Generator[LintError, None, None]]

class rstcheck_core.types.InlineConfig(*args, **kwargs)[source]

Bases: dict

Dict with a config key and config value comming from a inline config comment.

key: str
value: str
class rstcheck_core.types.InlineFlowControl(*args, **kwargs)[source]

Bases: dict

Dict with a flow control value and line number comming from a inline config comment.

value: str
line_number: int

FAQ / Known limitations / Known issues

Known limitations

There are inherent limitations to what rstcheck-core can and cannot do. The reason for this is that rstcheck-core itself relies on external tools for parsing and error reporting. The rst source e.g. is given to docutils which then parses it and returns the errors. Therefore rstcheck-core is more like an error accumulation tool. The same goes for the source code in supported code blocks.

Known issues

Code blocks without language (Sphinx)

According to the documentation for reStructuredText over at docutils the language is an optional argument to a code block directive. In vanilla mode language-less code blocks are treated like code blocks which specified a language that is not supported by rstcheck.

When sphinx support is active however, a deeply nested issue arises in form of an AttributeError. This exception has the unpleasant side-effect that linting for the whole file containing this language-less code block fails. This may result in a false negative for the file.

There are currently only one fix available:

Explicitly specifying the language for the code block. This renders the highlight directive useless, but is the only known way to fix this issue. And it enables checks of the source code inside those code blocks, if the language is supported of cause.

This issue is tracked in issue #3.

Migration-Guides

Only breaking changes are mentioned here. New features or fixes are only mentioned if they somehow correspond to a breaking change.

rstcheck v5 to rstcheck-core v1 (rc1)

Subject to change till final release

With version 6 the whole code base was restructured and the core library was moved into a separate repository. With it the whole open library API has changed. A simple migration is not possible. Please see the API section or open an issue if you have open questions.

Changelog

This is the changelog of rstcheck-core. Releases and their respective changes are listed here. The order of releases is time and not version based! For a list of all available releases see the tags section on Github. Links on the versions point to PyPI.

Unreleased

diff v1.0.3…main

Bugfixes

  • Auto discover pyproject.toml file on py311 and up

Miscellaneous

  • Ignore “no newline at end of file” errors when C++ code is checked by clang (such as on macOS) (#45)

  • Drop python 3.7 (#52)

  • Drop support for Sphinx v2 and v3 (#51)

  • Add tox environments for v6 adn v7 (#51)

1.0.3 (2022-11-12)

diff v1.0.2…v1.0.3

Documentation

  • Update release docs for changed release script

  • Restructure FAQ in docs

Miscellaneous

  • Fix release script’s changelog insertion

  • Add pre-commit-ci badge to README

  • Update development tooling dependencies

  • Update GHA workflows (#22)

  • Add support for python 3.11 (#21)

  • Update docutils version constraint (#20)

1.0.2 (2022-05-30)

diff v1.0.1.post2…v1.0.2

Miscellaneous

  • Add tox envs to test with sphinx v5.

  • Widen version range for sphinx extra to include v5.

  • Update sphinx extlinks config for v5.

  • Print error message on non-zero exit code (#15)

  • Add integration tests based off of cli tests from rstcheck cli app (#16)

1.0.1.post2 (2022-05-30)

diff v1.0.1.post1…v1.0.1.post2

Miscellaneous

  • Fix link for PyPI in changelog for 1.0.1 release.

  • Fix link for PyPI in release script.

1.0.1.post1 (2022-05-30)

diff v1.0.1…v1.0.1.post1

Miscellaneous

  • Update changelog with missing notes

1.0.1 (2022-05-30)

diff v1.0.0…v1.0.1

New features

  • Add function to create dummy Sphinx app (#13)

Bugfixes

  • Fix sourcecode directive being ignored, when Sphinx support is active (#13)

Documentation

  • Add section to FAQ about issue with language-less code blocks with sphinx (#13)

Miscellaneous

  • Changed log level for unparsable GCC style messages from WARNING to DEBUG to reduce noise.

  • Log CRITICAL on AttributeError with sphinx support on, which mostly probably comes from language-less code blocks (#13)

v1.0.0 (2022-05-29)

diff v1.0.0rc1…v1.0.0

New features

  • Non-existing paths are filtered out before checking and are logged as warning (#10)

  • Use <stdin> for source in error messages instead of - (#11)

  • Add constructor function for IgnoreDict (#12)

v1.0.0rc1 (2022-05-28)

diff split…v1.0.0

Authors

Author

Steven Myint <git@stevenmyint.com>

Additional contributions by (sorted by name)

License

Copyright (C) 2013-2022 Steven Myint

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.