Mastodon

Field notes

7 checks that keep a CLI guide in step with the CLI

Run auto-annotate twice on the same CVAT task, and 4 boxes become 8. Real output like that makes a CLI guide worth trusting, and a test keeps it true. Here's what I learned checking CVAT's command line guide against the CLI itself, as seven checks you can run on any CLI's docs.

· 7 checks · tested with cvat-cli 2.84.0

is an open-source tool for labelling images and video to train computer vision models. Its command line tool, cvat-cli, has a with 60 examples across 24 commands.

I wanted to see how a guide like that stays in step with the CLI as both change. So I built a small checker that tests the page against cvat-cli 2.84.0 itself, and ran the options it covers on CVAT Online with a test task. All 60 examples still parse, and every command has at least one. Here are the seven checks, each with what the runs returned.

Where the checks fit

The CLI
Check 1
The parser the command itself uses, from the version people install
The page
Checks 2, 3 and 4
Every example parses, every option is on the page, every command has an example
The guide and its CI
Checks 5, 6 and 7
Exit codes and real output in the guide, and a build that fails when the page drifts
Where each check fits between the CLI and its guide. Runs with cvat-cli 2.84.0, 25 November 2026.

1. Test against the CLI's own parser

Help text and docs are both copies. The parser is what users actually run. cvat-cli builds its argparse parser inside main() and parses straight away, so the checker runs main() with parse_args briefly swapped for a function that hands the finished parser back. No other cvat-cli code runs.

check_cli_docs.py, lines 72 to 98
def build_cli_parser() -> argparse.ArgumentParser:
    """Return the argument parser that the `cvat-cli` command itself uses.

    cvat-cli builds its parser inside main() and parses straight away. So main()
    is run with ArgumentParser.parse_args briefly replaced by a function that hands
    the finished parser back instead of parsing. No other cvat-cli code runs.
    """
    # Error messages and help start with the program name, which argparse takes
    # from sys.argv[0]. Make it read "cvat-cli", as it does for users.
    sys.argv[0] = "cvat-cli"

    from cvat_cli.__main__ import main

    original_parse_args = argparse.ArgumentParser.parse_args

    def hand_back_parser(self, *args, **kwargs):
        raise _ParserCaptured(self)

    argparse.ArgumentParser.parse_args = hand_back_parser
    try:
        main([])
    except _ParserCaptured as captured:
        return captured.parser
    finally:
        argparse.ArgumentParser.parse_args = original_parse_args

    raise RuntimeError("cvat-cli's main() finished without building its parser")

Because it uses the installed cvat-cli, the check follows the version people install. By default it fetches the guide at the CVAT tag that matches that version. On 25 November, the page was the same on develop and at v2.84.0.

2. Run every example through it, like a doctest

Each cvat-cli command shown on the page goes through that parser. A rejected example fails the check with argparse's own error message. Nothing is executed and nothing is sent to a server, so it needs no account and no token.

check_cli_docs.py, lines 274 to 298
def parse_example(parser: argparse.ArgumentParser, arguments: list[str]) -> str | None:
    """Run an example through cvat-cli's parser. Returns None if it's accepted,
    or argparse's error message if it isn't. Nothing is executed."""

    def reject(self, message):
        raise _ExampleRejected(f"{self.prog}: {message}")

    def stop(self, status=0, message=None):  # --help and --version end here
        raise _ParserExited()

    original_error = argparse.ArgumentParser.error
    original_exit = argparse.ArgumentParser.exit
    argparse.ArgumentParser.error = reject
    argparse.ArgumentParser.exit = stop
    try:
        with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
            parser.parse_args(arguments)
        return None
    except _ParserExited:
        return None
    except _ExampleRejected as rejected:
        return str(rejected)
    finally:
        argparse.ArgumentParser.error = original_error
        argparse.ArgumentParser.exit = original_exit

All 60 examples on CVAT's guide passed. One wrinkle: cvat-cli reads a --labels file while it parses, so the checker lets a missing .json file through, because the docs name files the reader would have, not files on the machine running the check.

3. Check that every option the CLI has is on the page

The checker walks every command the parser knows and looks for each of its options on the page. If the CLI drops an option, the examples that still use it fail check 2, so drift shows up in both directions.

The repo's proposed page adds what the guide didn't cover yet: a Common options table for --version, --insecure and --debug, an Exit codes section, and examples for the newer task and function options. Here's the checker's report on it:

reports/after.md
# CVAT CLI docs check

cvat-cli **2.84.0**, checked against `proposed-docs/_index.md`.

| Check | Result |
|---|---|
| Options the page never mentions | 0 |
| Examples cvat-cli rejects | 0 |
| Commands with no example | 0 |
| Examples checked and accepted | 68 |
| Options never shown in an example for their command (information) | 9 |

## Options never shown in an example for their command

These appear somewhere on the page, but not in an example for the command listed.

- `project create --bug_tracker`
- `project backup --completion_verification_period`
- `project create-from-backup --completion_verification_period`
- `project export-dataset --completion_verification_period`
- `task create --completion_verification_period`
- `task export-dataset --completion_verification_period`
- `task export-dataset --with-images`
- `task backup --completion_verification_period`
- `task create-from-backup --completion_verification_period`

**Result:** the page is in step with the CLI.

4. Give every command at least one example

People look up one command, not the whole page. The checker counts the examples for each command, and all 24 of cvat-cli's commands had at least one. With --strict, it also fails when an option appears on the page but never in an example for its own command: the 9 in the report above, which it otherwise lists as information.

5. Write down the exit codes, from real runs

Scripts and CI decide what to do next from a command's exit code, so the guide should say what each one means. Read them from the code, then confirm them with real runs, here with a fake token on purpose:

Exit codes, from real runs (shortened)
$ cvat-cli --version
2.84.0
[exit code: 0]

$ cvat-cli task ls --no-such-option
usage: cvat-cli [-h] [--version] [--insecure] [--auth USER[:PASS]]
...
cvat-cli: error: unrecognized arguments: --no-such-option
[exit code: 2]

$ CVAT_ACCESS_TOKEN=not-a-real-token cvat-cli --server-host http://localhost:9 task ls
[2026-11-25 20:28:37] CRITICAL: HTTPConnectionPool(host='localhost', port=9): Max retries exceeded with url: /api/server/about ...
[exit code: 1]

In the code, cvat_cli/__main__.py returns 1 when it catches ApiException, urllib3.exceptions.HTTPError, CriticalError or AuthStoreError, and 0 otherwise. argparse exits with 2 for an invalid command line, and with 0 after --help or --version.

6. Show what an option changes, with real output

A sentence says what an option does. Output shows it. I ran the auto-annotate options on CVAT Online with a 2-image task and a small test detector that finds a confident box (0.9) and an unsure one (0.3) in each image:

CVAT Online, 25 November 2026 (shortened)
$ cvat-cli --server-host https://app.cvat.ai task auto-annotate 2793027 --function-file .\examples\fake_detector.py --allow-unmatched-labels
...
[2026-11-25 21:12:21] INFO: Upload complete
[exit code: 0]
Boxes in the task now: 4

$ (the same command again)
...
[2026-11-25 21:12:29] INFO: Upload complete
[exit code: 0]
Boxes in the task now: 8

$ cvat-cli --server-host https://app.cvat.ai task auto-annotate 2793027 --function-file .\examples\fake_detector.py --allow-unmatched-labels --clear-existing --conf-threshold 0.5
...
[2026-11-25 21:12:38] INFO: Upload complete
[exit code: 0]
Boxes in the task now: 2

Run it again without --clear-existing, and the boxes add up. With --clear-existing and --conf-threshold 0.5, only the two confident boxes are left. The --allow-unmatched-labels option is there because the test detector declares a label the task doesn't have. And task create --subset Train did what it says:

task ls --json, the relevant fields
{
  "id": 2793027,
  "name": "cvat-cli docs check demo",
  "subset": "Train",
  "size": 2
}

The demo task was deleted at the end, and the access token never appeared in the output.

7. Fail the build when the page drifts

The checker exits with 0 when the page is in step and 1 when something needs fixing, so it can run in CI as a stale-content alert. The repo has a sketch for CVAT's docs workflow, which runs it whenever the CLI, the SDK or the page changes:

proposed-ci/cli-docs-check.yml
# A sketch for cvat-ai/cvat: run check_cli_docs.py whenever the CLI or its docs page changes,
# so the page can't fall behind the CLI again. It assumes the script is saved in the
# repository as dev/check_cli_docs.py.
#
# The install step is left as a comment: install cvat-sdk and cvat-cli from the checkout
# the same way the repository's existing SDK and CLI workflows do (the SDK is generated first).

name: CLI docs check

on:
  pull_request:
    paths:
      - "cvat-cli/**"
      - "cvat-sdk/**"
      - "site/content/en/docs/api_sdk/cli/**"

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      # Install cvat-sdk and cvat-cli from this checkout here.

      - name: Check the CLI page against the CLI
        run: >
          python dev/check_cli_docs.py
          --docs site/content/en/docs/api_sdk/cli/_index.md
          --markdown cli-docs-report.md

      - name: Keep the report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: cli-docs-report
          path: cli-docs-report.md

The checklist

  1. Test against the CLI's own parser.
  2. Run every example through it, like a doctest.
  3. Check that every option the CLI has is on the page.
  4. Give every command at least one example.
  5. Write down the exit codes, from real runs.
  6. Show what an option changes, with real output.
  7. Fail the build when the page drifts.

How I used AI

I used Claude Code throughout: to read the CLI's source, draft the checker and its tests, triage the guide's open documentation issues and draft the new sections. Then I checked its work the way I'd check a docs page. Every option and behaviour in the new text comes from the CLI's code or a real run, the checker verifies the page, and a spot-check of the issue triage caught one wrong claim before it went in.

The sample

Everything above comes from : the checker, 18 offline tests, the proposed page and its patch, the CI sketch, and transcripts of every real run. has notes for CVAT's team from the same runs, and a triage of the guide's open documentation issues.

check_cli_docs.py (516 lines)
check_cli_docs.py
#!/usr/bin/env python3
"""
check_cli_docs.py: keeps CVAT's CLI guide in step with the CVAT CLI itself.

It checks the CLI docs page (site/content/en/docs/api_sdk/cli/_index.md in the
cvat-ai/cvat repository) in two ways:

1. Does the page mention every option the CLI really has?
   The script builds cvat-cli's own argument parser, the same one the `cvat-cli`
   command uses, walks every command, and looks for each option on the page.

2. Does every `cvat-cli` example on the page still parse with the current CLI?
   Each example is run through that real parser. Nothing is executed and nothing
   is sent to a server. So a renamed option, a removed command or a missing
   argument shows up as a failure, like a doctest for the page.

Exit status: 0 when the page is in step, 1 when something needs fixing, 2 when
the script itself is used wrongly. That makes it usable as a CI check (a
"stale-content alert") in the docs workflow.

Usage:
    python check_cli_docs.py                    # the page for the installed cvat-cli version
    python check_cli_docs.py --docs site/content/en/docs/api_sdk/cli/_index.md
    python check_cli_docs.py --docs https://raw.githubusercontent.com/cvat-ai/cvat/develop/site/content/en/docs/api_sdk/cli/_index.md
    python check_cli_docs.py --markdown report.md

It needs only the Python standard library and an installed cvat-cli.
"""

from __future__ import annotations

import argparse
import contextlib
import io
import os
import re
import shlex
import sys
import urllib.request
from dataclasses import dataclass, field
from importlib.metadata import version as installed_version

# The docs page for a given cvat-cli release, read from the matching CVAT git tag.
DOCS_URL = (
    "https://raw.githubusercontent.com/cvat-ai/cvat/v{version}"
    "/site/content/en/docs/api_sdk/cli/_index.md"
)

# Placeholders in examples that stand for whole parts of the command line, such as
# "cvat-cli <common options> <resource> <action>". Examples with these are templates,
# not runnable commands, so they're skipped.
TEMPLATE_PLACEHOLDERS = ("<common options>", "<resource>", "<action>", "<options>")

# Any other placeholder, such as "<ID printed by previous command>", is replaced by
# "1" before parsing, which suits both IDs and file names.
PLACEHOLDER = re.compile(r"<[^<>\n]+>")


# ---------------------------------------------------------------------------
# 1. The real cvat-cli parser
# ---------------------------------------------------------------------------


class _ParserCaptured(Exception):
    """Carries the parser out of cvat-cli's main() before anything is parsed."""

    def __init__(self, parser: argparse.ArgumentParser):
        super().__init__()
        self.parser = parser


def build_cli_parser() -> argparse.ArgumentParser:
    """Return the argument parser that the `cvat-cli` command itself uses.

    cvat-cli builds its parser inside main() and parses straight away. So main()
    is run with ArgumentParser.parse_args briefly replaced by a function that hands
    the finished parser back instead of parsing. No other cvat-cli code runs.
    """
    # Error messages and help start with the program name, which argparse takes
    # from sys.argv[0]. Make it read "cvat-cli", as it does for users.
    sys.argv[0] = "cvat-cli"

    from cvat_cli.__main__ import main

    original_parse_args = argparse.ArgumentParser.parse_args

    def hand_back_parser(self, *args, **kwargs):
        raise _ParserCaptured(self)

    argparse.ArgumentParser.parse_args = hand_back_parser
    try:
        main([])
    except _ParserCaptured as captured:
        return captured.parser
    finally:
        argparse.ArgumentParser.parse_args = original_parse_args

    raise RuntimeError("cvat-cli's main() finished without building its parser")


@dataclass
class Command:
    """One command of the CLI, such as `task auto-annotate`."""

    path: tuple[str, ...]  # ("task", "auto-annotate"); () is cvat-cli itself
    parser: argparse.ArgumentParser
    options: list[argparse.Action]  # its --options (help is left out)
    subcommands: dict[str, argparse.ArgumentParser] = field(default_factory=dict)

    @property
    def name(self) -> str:
        return " ".join(self.path) or "cvat-cli"


def walk_commands(parser: argparse.ArgumentParser, path: tuple[str, ...] = ()):
    """Yield the given parser's command, then every command below it."""
    command = Command(path, parser, [])
    for action in parser._actions:
        if isinstance(action, argparse._SubParsersAction):
            command.subcommands.update(action.choices)
        elif action.option_strings and not isinstance(action, argparse._HelpAction):
            command.options.append(action)
    yield command
    for name, subparser in command.subcommands.items():
        yield from walk_commands(subparser, path + (name,))


def is_deprecated_alias(command: Command) -> bool:
    """True for the old top-level shortcuts such as `cvat-cli ls`.

    The docs say these exist only for backwards compatibility and are deprecated,
    so the page isn't expected to document them. They're the top-level commands
    that have no subcommands of their own (`task`, `project` and the rest do).
    """
    return len(command.path) == 1 and not command.subcommands


def help_text(command: Command, action: argparse.Action) -> str:
    """The option's help text as `--help` shows it, on one line."""
    if not action.help:
        return ""
    try:
        text = command.parser._get_formatter()._expand_help(action)
    except (KeyError, TypeError, ValueError):
        text = action.help
    return " ".join(text.split())


def is_hidden(action: argparse.Action) -> bool:
    """Options hidden from --help on purpose don't need documenting."""
    return action.help == argparse.SUPPRESS


# ---------------------------------------------------------------------------
# 2. The docs page and its examples
# ---------------------------------------------------------------------------


def load_docs(source: str) -> str:
    """Read the page from a file path or an http(s) URL."""
    if re.match(r"^https?://", source):
        with urllib.request.urlopen(source, timeout=30) as response:
            return response.read().decode("utf-8")
    with open(source, encoding="utf-8") as page:
        return page.read()


@dataclass
class Example:
    """One `cvat-cli` command shown in a code block on the page."""

    line: int  # line number on the page where the command starts
    text: str  # the command as written, with continuation lines joined
    section: str  # the headings above it, such as "Examples - tasks > Auto-annotate"
    arguments: list[str] | None = None  # what cvat-cli would receive; None for templates
    command: Command | None = None  # the CLI command it runs, once identified
    error: str | None = None  # why cvat-cli rejects it, if it does


def find_examples(page: str) -> list[Example]:
    """Collect every `cvat-cli` command line from the page's fenced code blocks.

    Commands may start with "$ " or with environment variables
    (`PYTHONPATH=dir cvat-cli ...`), and may continue over several lines with "\\".
    JSON and Python blocks are skipped.
    """
    examples: list[Example] = []
    headings = {2: "", 3: ""}
    in_code = False
    language = ""
    continuing: Example | None = None

    for number, raw_line in enumerate(page.splitlines(), start=1):
        line = raw_line.strip()

        if line.startswith("```"):
            in_code = not in_code
            language = line[3:].strip().lower() if in_code else ""
            continuing = None
            continue

        if not in_code:
            heading = re.match(r"^(#{2,3})\s+(.*)", line)
            if heading:
                level = len(heading.group(1))
                headings[level] = heading.group(2).strip()
                if level == 2:
                    headings[3] = ""
            continue

        if language in ("json", "jsonc", "python", "py"):
            continue

        if continuing:
            continuing.text += " " + line.rstrip("\\").strip()
            if not line.endswith("\\"):
                continuing = None
            continue

        command = re.sub(r"^\$\s*", "", line)
        if re.match(r"^(\w+=\S*\s+)*cvat-cli(\s|$)", command):
            section = " > ".join(part for part in (headings[2], headings[3]) if part)
            example = Example(number, command.rstrip("\\").strip(), section)
            examples.append(example)
            if command.endswith("\\"):
                continuing = example

    return examples


def to_arguments(text: str) -> list[str] | None:
    """Split an example into the arguments cvat-cli would receive.

    Returns None for templates such as `cvat-cli <resource> <action> --help`.
    """
    if any(template in text for template in TEMPLATE_PLACEHOLDERS):
        return None

    # Split the way a shell would, so quotes are handled. punctuation_chars makes
    # shell operators such as ">" and "|" separate words, so the cvat-cli command
    # can stop there: in `cvat-cli task ls --json > tasks.json`, the
    # "> tasks.json" part is for the shell, not for cvat-cli.
    lexer = shlex.shlex(PLACEHOLDER.sub("1", text), posix=True, punctuation_chars=True)
    lexer.whitespace_split = True
    words = []
    for word in lexer:  # "#" comments are dropped by the lexer
        if word and set(word) <= set("();<>|&"):
            break
        words.append(word)

    while words and re.match(r"^\w+=", words[0]):  # environment variables
        words.pop(0)
    return words[1:]  # everything after "cvat-cli"


def find_command(commands: dict[tuple[str, ...], Command], arguments: list[str]) -> Command:
    """Work out which CLI command an example runs, from its subcommand words."""
    path: tuple[str, ...] = ()
    for word in arguments:
        current = commands[path]
        if word in current.subcommands:
            path = path + (word,)
    return commands[path]


class _ExampleRejected(Exception):
    pass


class _ParserExited(Exception):
    pass


def parse_example(parser: argparse.ArgumentParser, arguments: list[str]) -> str | None:
    """Run an example through cvat-cli's parser. Returns None if it's accepted,
    or argparse's error message if it isn't. Nothing is executed."""

    def reject(self, message):
        raise _ExampleRejected(f"{self.prog}: {message}")

    def stop(self, status=0, message=None):  # --help and --version end here
        raise _ParserExited()

    original_error = argparse.ArgumentParser.error
    original_exit = argparse.ArgumentParser.exit
    argparse.ArgumentParser.error = reject
    argparse.ArgumentParser.exit = stop
    try:
        with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
            parser.parse_args(arguments)
        return None
    except _ParserExited:
        return None
    except _ExampleRejected as rejected:
        return str(rejected)
    finally:
        argparse.ArgumentParser.error = original_error
        argparse.ArgumentParser.exit = original_exit


def allow_missing_label_files(commands: list[Command]) -> None:
    """Let `--labels labels.json` parse when labels.json isn't on this machine.

    cvat-cli reads the labels file while it parses the command line. The docs name
    files the reader would have, not files that exist here, so for this check a
    missing .json file counts as fine. Inline JSON is still parsed for real.
    """
    for command in commands:
        for action in command.options:
            original = action.type
            if getattr(original, "__name__", "") != "parse_label_arg":
                continue

            def lenient(value, original=original):
                if value.endswith(".json") and not os.path.exists(value):
                    return value
                return original(value)

            lenient.__name__ = original.__name__
            action.type = lenient


# ---------------------------------------------------------------------------
# 3. Comparing the CLI with the page
# ---------------------------------------------------------------------------


def mentioned(page: str, option_string: str) -> bool:
    """True if the option appears on the page as a whole word (`--format`, `-p`)."""
    return re.search(rf"(?<![\w-]){re.escape(option_string)}(?![\w-])", page) is not None


@dataclass
class Report:
    cli_version: str
    docs_source: str
    never_mentioned: list[tuple[Command, argparse.Action]] = field(default_factory=list)
    not_in_examples: list[tuple[Command, argparse.Action]] = field(default_factory=list)
    commands_without_examples: list[Command] = field(default_factory=list)
    examples: list[Example] = field(default_factory=list)

    @property
    def rejected_examples(self) -> list[Example]:
        return [example for example in self.examples if example.error]

    def problems(self, strict: bool) -> int:
        count = len(self.never_mentioned) + len(self.rejected_examples)
        count += len(self.commands_without_examples)
        if strict:
            count += len(self.not_in_examples)
        return count


def compare(page: str, docs_source: str, include_aliases: bool) -> Report:
    parser = build_cli_parser()
    all_commands = list(walk_commands(parser))
    by_path = {command.path: command for command in all_commands}
    report = Report(installed_version("cvat-cli"), docs_source)

    # Run every example through the real parser.
    allow_missing_label_files(all_commands)
    for example in find_examples(page):
        example.arguments = to_arguments(example.text)
        if example.arguments is not None:
            example.command = find_command(by_path, example.arguments)
            example.error = parse_example(parser, example.arguments)
        report.examples.append(example)

    # The options each command is shown with in accepted examples.
    shown: dict[tuple[str, ...], set[str]] = {}
    for example in report.examples:
        if example.command and not example.error:
            words = {word.split("=", 1)[0] for word in example.arguments if word.startswith("-")}
            shown.setdefault(example.command.path, set()).update(words)

    root = by_path[()]
    for command in all_commands:
        if is_deprecated_alias(command) and not include_aliases:
            continue
        is_runnable = not command.subcommands
        if is_runnable and command.path not in shown:
            report.commands_without_examples.append(command)
        for action in command.options:
            if is_hidden(action):
                continue
            if not any(mentioned(page, s) for s in action.option_strings):
                report.never_mentioned.append((command, action))
            elif command is not root and not set(action.option_strings) & shown.get(command.path, set()):
                report.not_in_examples.append((command, action))

    return report


# ---------------------------------------------------------------------------
# 4. Output
# ---------------------------------------------------------------------------


def option_label(command: Command, action: argparse.Action) -> str:
    longest = max(action.option_strings, key=len)
    prefix = "cvat-cli" if not command.path else command.name
    return f"{prefix} {longest}"


def text_report(report: Report, strict: bool) -> str:
    accepted = [e for e in report.examples if e.arguments is not None and not e.error]
    templates = [e for e in report.examples if e.arguments is None]
    lines = [
        f"cvat-cli {report.cli_version}, checked against {report.docs_source}",
        "",
        f"Options the page never mentions: {len(report.never_mentioned)}",
    ]
    width = max((len(option_label(c, a)) for c, a in report.never_mentioned), default=0)
    for command, action in report.never_mentioned:
        lines.append(f"  {option_label(command, action):<{width}}  {help_text(command, action)}")
    lines += ["", f"Examples cvat-cli rejects: {len(report.rejected_examples)}"]
    for example in report.rejected_examples:
        lines.append(f"  line {example.line} ({example.section}): {example.text}")
        lines.append(f"    {example.error}")
    lines += ["", f"Commands with no example: {len(report.commands_without_examples)}"]
    lines += [f"  {command.name}" for command in report.commands_without_examples]
    lines += [
        "",
        f"Examples checked: {len(accepted) + len(report.rejected_examples)} "
        f"({len(accepted)} accepted), plus {len(templates)} templates skipped",
        "",
        f"Mentioned on the page, but never in an example for that command: "
        f"{len(report.not_in_examples)}" + ("" if strict else " (for information; --strict counts these)"),
    ]
    for command, action in report.not_in_examples:
        lines.append(f"  {option_label(command, action)}")
    problems = report.problems(strict)
    lines += ["", "Result: the page is in step with the CLI." if not problems else f"Result: {problems} problems to fix."]
    return "\n".join(lines)


def markdown_report(report: Report, strict: bool) -> str:
    def cell(text: str) -> str:
        return text.replace("|", "\\|")

    accepted = [e for e in report.examples if e.arguments is not None and not e.error]
    lines = [
        "# CVAT CLI docs check",
        "",
        f"cvat-cli **{report.cli_version}**, checked against `{report.docs_source}`.",
        "",
        "| Check | Result |",
        "|---|---|",
        f"| Options the page never mentions | {len(report.never_mentioned)} |",
        f"| Examples cvat-cli rejects | {len(report.rejected_examples)} |",
        f"| Commands with no example | {len(report.commands_without_examples)} |",
        f"| Examples checked and accepted | {len(accepted)} |",
        f"| Options never shown in an example for their command (information) | {len(report.not_in_examples)} |",
        "",
    ]
    if report.never_mentioned:
        lines += ["## Options the page never mentions", "", "| Option | Help text |", "|---|---|"]
        for command, action in report.never_mentioned:
            lines.append(f"| `{option_label(command, action)}` | {cell(help_text(command, action))} |")
        lines.append("")
    if report.rejected_examples:
        lines += ["## Examples cvat-cli rejects", "", "| Line | Example | Error |", "|---|---|---|"]
        for example in report.rejected_examples:
            lines.append(f"| {example.line} | `{cell(example.text)}` | {cell(example.error)} |")
        lines.append("")
    if report.commands_without_examples:
        lines += ["## Commands with no example", ""]
        lines += [f"- `{command.name}`" for command in report.commands_without_examples]
        lines.append("")
    if report.not_in_examples:
        lines += ["## Options never shown in an example for their command", ""]
        lines.append("These appear somewhere on the page, but not in an example for the command listed.")
        lines.append("")
        lines += [f"- `{option_label(command, action)}`" for command, action in report.not_in_examples]
        lines.append("")
    problems = report.problems(strict)
    lines.append("**Result:** the page is in step with the CLI." if not problems else f"**Result:** {problems} problems to fix.")
    return "\n".join(lines) + "\n"


def main(argv: list[str] | None = None) -> int:
    arguments = argparse.ArgumentParser(
        description="Check CVAT's CLI docs page against the installed cvat-cli."
    )
    arguments.add_argument(
        "--docs",
        help="the docs page to check, as a file path or URL "
        "(default: the page for the installed cvat-cli version, from GitHub)",
    )
    arguments.add_argument("--markdown", metavar="FILE", help="also write a Markdown report to FILE")
    arguments.add_argument(
        "--strict",
        action="store_true",
        help="also fail when an option is never shown in an example for its own command",
    )
    arguments.add_argument(
        "--include-aliases",
        action="store_true",
        help="also check the deprecated top-level shortcuts, such as `cvat-cli ls`",
    )
    options = arguments.parse_args(argv)

    docs_source = options.docs or DOCS_URL.format(version=installed_version("cvat-cli"))
    report = compare(load_docs(docs_source), docs_source, options.include_aliases)

    print(text_report(report, options.strict))
    if options.markdown:
        os.makedirs(os.path.dirname(os.path.abspath(options.markdown)), exist_ok=True)
        with open(options.markdown, "w", encoding="utf-8") as output:
            output.write(markdown_report(report, options.strict))

    return 1 if report.problems(options.strict) else 0


if __name__ == "__main__":
    sys.exit(main())

To run it, you need Python and cvat-cli. The checker itself uses only the standard library, and the README has the steps.

Your turn

Which of the seven does your docs CI run today?

If you maintain a CLI, an SDK or the docs for one, I'd like to hear what you'd add to this list.

Get in touch

From the same kind of hands-on testing: 7 checks before a hotel booking API goes live, 7 checks before a game payments integration goes live, and 7 checks before a shopping agent trusts the cheapest price.