Skip to main content

A Sphinx extension to expose code blocks to external tools for linting

Project description

Sphinx awesome codelinter

License PyPI version

The awesome codelinter extension for the Sphinx documentation generator lets you verify that code blocks are valid or follow a preferred style. The extension lets you run external tools, such as linters, over all code blocks in your Sphinx documentation.

Install

Install the extension:

pip install sphinxawesome-codelinter

Requirements:

  • Python >= 3.9
  • Sphinx >= 7

Configure

To use this extension, add it to the list of extensions in your Sphinx configuration file conf.py:

extensions += ["sphinxawesome.codelinter"]

To use an external tool to check code blocks, add the language and tool as key-value pairs to the codelinter_languages dictionary. By default, the dictionary is empty, so no code blocks will be processed unless added.

For example, to pass all JSON blocks to Python's built-in JSON module, use:

codelinter_languages = {"json": "python -m json.tool"}

The Python command python -m json.tool returns an error for non-valid JSON code. To lint YAML code blocks, install the yamllint tool and add:

codelinter_languages = {"yaml": "yamllint -"}

The - tells yamllint to read from stdin. You can write your own tools that read from stdin and write to stdout or stderr. They should return 0 if no errors are found, a non-zero value otherwise.

You can use any reStructuredText directive that gets parsed as a literal_block node. For example, you can use .. code-block:: json, .. code:: json, or ..literalinclude:: <filename> to include code from files.

.. literalinclude:: code.json
   :language: json

[!CAUTION] The command you add to the codelinter_languages dictionary is called as you provide it. No additional safe-guards are in place to prevent abuse.

Use

Run sphinx-build -b codelinter to check your code blocks. If any tool returns a non-zero value, a warning is logged. To turn warnings into errors and stop the build process, use sphinx-build -W.

Bring your own tools

Since the codelinter_languages dictionary accepts any program, you're not limited to existing solutions.

The following example runs a custom linter on Python and C code blocks. It shows how you can achieve the following tasks:

  • Check that Python code passes mypy checks. Mypy doesn't support reading from standard input, so you can't use it directly.
  • Check that C code can compile without warnings.
  • Add C boilerplate code if there's a special comment in the code block.
  • Opt out of linting specific code blocks if there's a special comment.
# File: docs/linters.py
import argparse
import subprocess
import sys

python_code_preface = """
import numpy as np
import customlib
"""


def lint_python(code: str) -> None:
    full_code = python_code_preface + code
    if "# no-check" in full_code:  # skip checking
        return
    subprocess.run(["mypy", "-c", f"{full_code}"], check=True)


def lint_c(code: str) -> None:
    if "// no-check" in code:  # skip checking
        return

    # it is a full example
    if "// full" in code:
        full_code = (
            """
#include <stdlib.h>
#include <stdio.h>
"""
            + code
        )
    else:
        full_code = (
            """
#include <stdlib.h>
#include <stdio.h>

int main() {
"""
            + code
            + """
    return 0;
}
"""
        )
    subprocess.run(
        [
            "gcc",
            "-c",
            "-x",
            "c",
            "-Wall",
            "-Werror",
            "-ansi",
            "-std=c99",
            "-pedantic",
            "-pedantic-errors",
            "-Wno-unused-variable",
            "-Wno-unused-but-set-variable",
            "-Wno-unused-local-typedefs",
            "-o",
            "/dev/null",
            "-",
        ],
        input=full_code.encode(),
        check=True,
    )


def main() -> None:
    parser = argparse.ArgumentParser()

    parser.add_argument("linter", choices=("python", "c"))
    args = parser.parse_args()
    code = sys.stdin.read()

    if args.linter == "python":
        lint_python(code)
    else:
        lint_c(code)


if __name__ == "__main__":
    main()

To use this linter, add the following to your Sphinx configuration:

# File: conf.py
codelinter_languages = {
    "python": "python -m docs.linters python",
    "c": "python -m docs.linters c",
}

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sphinxawesome_codelinter-3.0.1.tar.gz (73.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sphinxawesome_codelinter-3.0.1-py3-none-any.whl (5.9 kB view details)

Uploaded Python 3

File details

Details for the file sphinxawesome_codelinter-3.0.1.tar.gz.

File metadata

  • Download URL: sphinxawesome_codelinter-3.0.1.tar.gz
  • Upload date:
  • Size: 73.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for sphinxawesome_codelinter-3.0.1.tar.gz
Algorithm Hash digest
SHA256 6000c5fb24c34a613d591e345167390d50b225b36e1596ae8a6b86876ab4d3c4
MD5 b9ca3671f405b2d3e9248e7d63b99190
BLAKE2b-256 819d6de5baded32a529f070b12adf3a53258572a378b5e828bb2ce94c65ab10c

See more details on using hashes here.

Provenance

The following attestation bundles were made for sphinxawesome_codelinter-3.0.1.tar.gz:

Publisher: ci.yml on kai687/sphinxawesome-codelinter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file sphinxawesome_codelinter-3.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for sphinxawesome_codelinter-3.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 144607fc08a56692181c0b21157597c4f992a37bcb3443af9c5730af32dc24cb
MD5 9daa7f704394e96fe2e1300b76e795de
BLAKE2b-256 36893a2afe6f39314a8ab073bda463d4c8af36bdb2ae8f8e00c97e2214f8111e

See more details on using hashes here.

Provenance

The following attestation bundles were made for sphinxawesome_codelinter-3.0.1-py3-none-any.whl:

Publisher: ci.yml on kai687/sphinxawesome-codelinter

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page