├── mkdocs_typer ├── py.typed ├── __version__.py ├── _exceptions.py ├── __init__.py ├── _loader.py ├── _processing.py ├── _extension.py └── _docs.py ├── CHANGELOG.md ├── pyproject.toml ├── scripts ├── docs ├── format ├── test ├── build ├── style ├── install └── publish ├── tests ├── __init__.py ├── app │ ├── __init__.py │ ├── cli.py │ ├── bar.py │ └── expected.md ├── unit │ ├── __init__.py │ ├── test_loader.py │ ├── test_docs.py │ └── test_processing.py └── test_extension.py ├── MANIFEST.in ├── mkdocs.yml ├── requirements.txt ├── setup.cfg ├── .github └── workflows │ ├── publish.yml │ └── tests.yaml ├── CONTRIBUTING.md ├── setup.py ├── .gitignore ├── README.md └── LICENSE /mkdocs_typer/py.typed: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | line-length = 120 3 | target-version = ["py37"] 4 | -------------------------------------------------------------------------------- /scripts/docs: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | BIN="venv/bin/" 4 | 5 | set -x 6 | 7 | ${BIN}mkdocs "$@" 8 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | -------------------------------------------------------------------------------- /tests/app/__init__.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | include CHANGELOG.md 3 | include LICENSE 4 | include mkdocs_typer/py.typed 5 | -------------------------------------------------------------------------------- /mkdocs_typer/__version__.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | __version__ = "0.0.3" 4 | -------------------------------------------------------------------------------- /scripts/format: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | BIN="venv/bin/" 4 | FILES="mkdocs_typer tests" 5 | 6 | set -x 7 | 8 | ${BIN}black $FILES 9 | -------------------------------------------------------------------------------- /mkdocs_typer/_exceptions.py: -------------------------------------------------------------------------------- 1 | class MkDocsTyperException(Exception): 2 | """ 3 | Generic exception class for mkdocs-typer errors. 4 | """ 5 | -------------------------------------------------------------------------------- /scripts/test: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | VENV="venv" 4 | BIN="$VENV/bin/" 5 | 6 | set -x 7 | 8 | ${BIN}pytest "$@" 9 | 10 | scripts/style 11 | -------------------------------------------------------------------------------- /scripts/build: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | BIN="venv/bin/" 4 | 5 | set -x 6 | 7 | ${BIN}python setup.py sdist bdist_wheel 8 | ${BIN}twine check dist/* 9 | 10 | rm -r build 11 | -------------------------------------------------------------------------------- /scripts/style: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | BIN="venv/bin/" 4 | FILES="mkdocs_typer tests" 5 | 6 | set -x 7 | 8 | ${BIN}black --check --diff $FILES 9 | ${BIN}flake8 $FILES 10 | ${BIN}mypy $FILES 11 | -------------------------------------------------------------------------------- /scripts/install: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | VENV="venv" 4 | BIN="$VENV/bin/" 5 | 6 | set -x 7 | 8 | python3 -m venv $VENV 9 | 10 | ${BIN}pip install -U pip 11 | ${BIN}pip install -r requirements.txt 12 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | # NOTE: this is not an actual docs site for `mkdocs-typer`, but rather a 2 | # demo site to demonstrate the abilities of `mkdocs-typer`. 3 | site_name: mkdocs-typer example 4 | theme: readthedocs 5 | 6 | docs_dir: example 7 | 8 | markdown_extensions: 9 | - mkdocs-typer 10 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -e . 2 | 3 | # Packaging 4 | twine 5 | wheel 6 | 7 | # Linters 8 | black==23.3.0 9 | flake8==3.9.2 10 | importlib-metadata==4.13.0 11 | 12 | # Type checking 13 | mypy==0.950 14 | types-Markdown 15 | 16 | 17 | # Testing 18 | mock==4.0.2 19 | pytest==7.1.2 20 | pytest-cov==3.0.0 21 | -------------------------------------------------------------------------------- /mkdocs_typer/__init__.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | from .__version__ import __version__ 4 | from ._exceptions import MkDocsTyperException 5 | from ._extension import MKTyperExtension, makeExtension 6 | 7 | __all__ = ["__version__", "MKTyperExtension", "MkDocsTyperException", "makeExtension"] 8 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [flake8] 2 | ignore = E203,E722,E741,W503 3 | max-line-length = 120 4 | 5 | [mypy] 6 | disallow_untyped_defs = True 7 | ignore_missing_imports = True 8 | 9 | [mypy-tests.*] 10 | disallow_untyped_defs = False 11 | check_untyped_defs = True 12 | 13 | [tool:pytest] 14 | addopts = 15 | -rxXs 16 | --cov=mkdocs_typer 17 | --cov=tests 18 | --cov-report=term-missing 19 | --cov-fail-under=95 20 | -------------------------------------------------------------------------------- /scripts/publish: -------------------------------------------------------------------------------- 1 | #! /bin/sh -e 2 | 3 | PACKAGE="mkdocs_typer" 4 | BIN="venv/bin/" 5 | 6 | if [ "$GITHUB_ACTIONS" ]; then 7 | VERSION=`${BIN}python -c "import $PACKAGE; print($PACKAGE.__version__)"` 8 | 9 | if [ "${GITHUB_REF}" != "refs/tags/${VERSION}" ]; then 10 | echo "GitHub ref '${GITHUB_REF}' does not match package version '${VERSION}'" 11 | exit 1 12 | fi 13 | fi 14 | 15 | set -x 16 | 17 | ${BIN}twine upload dist/* 18 | -------------------------------------------------------------------------------- /tests/app/cli.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | import typer 4 | 5 | from tests.app import bar 6 | 7 | NOT_A_COMMAND = "not-a-command" 8 | 9 | my_app = typer.Typer(add_completion=False) 10 | my_app.add_typer(bar.app, name="bar") 11 | 12 | 13 | @my_app.command() 14 | def foo(): 15 | pass # pragma: no cover 16 | 17 | 18 | @my_app.callback() 19 | def cli(): 20 | """ 21 | Main entrypoint for this dummy program 22 | """ 23 | -------------------------------------------------------------------------------- /tests/app/bar.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | import typer 4 | 5 | 6 | app = typer.Typer() 7 | 8 | 9 | @app.callback() 10 | def bar(): 11 | """The bar command""" 12 | 13 | 14 | @app.command() 15 | def hello( 16 | count: int = typer.Option(default=1, help="Number of greetings.", show_default=False), 17 | name: str = typer.Option(..., prompt="Your name", help="The person to greet."), 18 | ): 19 | """Simple program that greets NAME for a total of COUNT times.""" 20 | -------------------------------------------------------------------------------- /tests/app/expected.md: -------------------------------------------------------------------------------- 1 | # my_app 2 | 3 | Main entrypoint for this dummy program 4 | 5 | Usage: 6 | 7 | ``` 8 | cli [OPTIONS] COMMAND [ARGS]... 9 | ``` 10 | 11 | ## bar 12 | 13 | The bar command 14 | 15 | Usage: 16 | 17 | ``` 18 | cli bar [OPTIONS] COMMAND [ARGS]... 19 | ``` 20 | 21 | ### hello 22 | 23 | Simple program that greets NAME for a total of COUNT times. 24 | 25 | Usage: 26 | 27 | ``` 28 | cli bar hello [OPTIONS] 29 | ``` 30 | 31 | Options: 32 | 33 | ``` 34 | --count INTEGER Number of greetings. 35 | --name TEXT The person to greet. [required] 36 | ``` 37 | 38 | ## foo 39 | 40 | Usage: 41 | 42 | ``` 43 | cli foo [OPTIONS] 44 | ``` 45 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Publish 3 | 4 | on: 5 | push: 6 | tags: 7 | - '*' 8 | 9 | jobs: 10 | publish: 11 | name: "Publish to PyPI" 12 | runs-on: "ubuntu-22.04" 13 | 14 | steps: 15 | - uses: "actions/checkout@v2" 16 | - uses: "actions/setup-python@v2" 17 | with: 18 | python-version: 3.8 19 | - name: "Install dependencies" 20 | run: scripts/install 21 | - name: "Build package artifacts" 22 | run: scripts/build 23 | - name: "Publish to PyPI" 24 | run: scripts/publish 25 | env: 26 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 27 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 28 | -------------------------------------------------------------------------------- /tests/unit/test_loader.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | from contextlib import nullcontext 4 | 5 | import pytest 6 | 7 | from mkdocs_typer._exceptions import MkDocsTyperException 8 | from mkdocs_typer._loader import load_command 9 | 10 | 11 | @pytest.mark.parametrize( 12 | "module, command, exc", 13 | [ 14 | pytest.param("tests.app.cli", "my_app", None, id="ok"), 15 | pytest.param("tests.app.cli", "doesnotexist", MkDocsTyperException, id="command-does-not-exist"), 16 | pytest.param("doesnotexist", "cli", ImportError, id="module-does-not-exist"), 17 | pytest.param("tests.app.cli", "NOT_A_COMMAND", MkDocsTyperException, id="not-a-command"), 18 | ], 19 | ) 20 | def test_load_command(module: str, command: str, exc): 21 | with pytest.raises(exc) if exc is not None else nullcontext(): # type: ignore 22 | load_command(module, command) 23 | -------------------------------------------------------------------------------- /.github/workflows/tests.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | name: Tests 3 | 4 | on: 5 | push: 6 | branches: ["main"] 7 | pull_request: 8 | branches: ["main"] 9 | 10 | jobs: 11 | tests: 12 | name: "Python ${{ matrix.python-version }}" 13 | runs-on: "ubuntu-22.04" 14 | 15 | strategy: 16 | matrix: 17 | python-version: ["3.7", "3.8", "3.9", "3.10"] 18 | 19 | steps: 20 | - uses: "actions/checkout@v3" 21 | - uses: "actions/setup-python@v4" 22 | with: 23 | python-version: "${{ matrix.python-version }}" 24 | - uses: "actions/cache@v2" 25 | with: 26 | path: ~/.pip/cache 27 | key: ${{ runner.os }}-pip-${{ hashFiles('requirements.txt') }} 28 | restore-keys: | 29 | ${{ runner.os }}-pip- 30 | ${{ runner.os }}- 31 | 32 | - name: "Install dependencies" 33 | run: scripts/install 34 | - name: "Run tests" 35 | run: scripts/test 36 | -------------------------------------------------------------------------------- /mkdocs_typer/_loader.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | import importlib 4 | from typing import Any 5 | 6 | import typer 7 | from ._exceptions import MkDocsTyperException 8 | 9 | 10 | def load_command(module: str, attribute: str) -> typer.main.Typer: 11 | """ 12 | Load and return the Typer object located at ':'. 13 | """ 14 | command = _load_obj(module, attribute) 15 | 16 | if not isinstance(command, typer.main.Typer): 17 | raise MkDocsTyperException(f"{attribute!r} must be a 'typer.main.Typer' object, got {type(command)}") 18 | 19 | return command 20 | 21 | 22 | def _load_obj(module: str, attribute: str) -> Any: 23 | try: 24 | mod = importlib.import_module(module) 25 | except SystemExit: 26 | raise MkDocsTyperException("the module appeared to call sys.exit()") # pragma: no cover 27 | 28 | try: 29 | return getattr(mod, attribute) 30 | except AttributeError: 31 | raise MkDocsTyperException(f"Module {module!r} has no attribute {attribute!r}") 32 | -------------------------------------------------------------------------------- /tests/unit/test_docs.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | from textwrap import dedent 4 | 5 | import typer 6 | 7 | from mkdocs_typer._docs import make_command_docs 8 | 9 | 10 | app = typer.Typer(add_completion=False) 11 | 12 | 13 | @app.command() 14 | def hello(debug: bool = typer.Option(False, "--debug/--no-debug", "-d", help="Include debug output")): 15 | """Hello, world!""" 16 | 17 | 18 | HELLO_EXPECTED = dedent( 19 | """ 20 | # hello 21 | 22 | Hello, world! 23 | 24 | Usage: 25 | 26 | ``` 27 | hello [OPTIONS] 28 | ``` 29 | 30 | Options: 31 | 32 | ``` 33 | -d, --debug / --no-debug Include debug output [default: no-debug] 34 | ``` 35 | 36 | """ 37 | ).strip() 38 | 39 | 40 | def test_make_command_docs(): 41 | output = "\n".join(make_command_docs("hello", app)).strip() 42 | assert output == HELLO_EXPECTED 43 | 44 | 45 | def test_depth(): 46 | output = "\n".join(make_command_docs("hello", app, level=2)).strip() 47 | assert output == HELLO_EXPECTED.replace("# ", "### ") 48 | 49 | 50 | def test_prog_name(): 51 | output = "\n".join(make_command_docs("hello-world", app)).strip() 52 | assert output == HELLO_EXPECTED.replace("# hello", "# hello-world") 53 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing guidelines 2 | 3 | Thank you for being interested in contributing to this project! Here's how to get started. 4 | 5 | ## Setup 6 | 7 | To start developing on this project, create a fork of this repository on GitHub, then clone your fork on your machine: 8 | 9 | ```bash 10 | git clone https://github.com//mkdocs-typer 11 | ``` 12 | 13 | You can now install development dependencies using: 14 | 15 | ```bash 16 | cd mkdocs-typer 17 | scripts/install 18 | ``` 19 | 20 | ## Example docs site 21 | 22 | You can run the example docs site that lives in `example/` locally using: 23 | 24 | ```bash 25 | scripts/docs serve 26 | ``` 27 | 28 | ## Testing and linting 29 | 30 | Once dependencies are installed, you can run the test suite using: 31 | 32 | ```bash 33 | scripts/test 34 | ``` 35 | 36 | You can run code auto-formatting using: 37 | 38 | ```bash 39 | scripts/format 40 | ``` 41 | 42 | To run style checks, use: 43 | 44 | ```bash 45 | scripts/style 46 | ``` 47 | 48 | ## Releasing 49 | 50 | _This section is for maintainers._ 51 | 52 | Before releasing a new version, create a pull request with: 53 | 54 | - An update to the changelog. 55 | - A version bump: see `__version__.py`. 56 | 57 | Merge the release PR, then create a release on GitHub. A tag will be created which will trigger a GitHub action to publish the new release to PyPI. 58 | -------------------------------------------------------------------------------- /mkdocs_typer/_processing.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | import re 4 | from typing import Callable, Iterable, Iterator 5 | 6 | 7 | def replace_blocks(lines: Iterable[str], title: str, replace: Callable[..., Iterable[str]]) -> Iterator[str]: 8 | """ 9 | Find blocks of lines in the form of: 10 | 11 | ::: 12 | :<key1>: <value> 13 | :<key2>: 14 | ... 15 | 16 | And replace them with the lines returned by `replace(key1="<value1>", key2="", ...)`. 17 | """ 18 | 19 | options = {} 20 | in_block_section = False 21 | 22 | for line in lines: 23 | if in_block_section: 24 | match = re.search(r"^\s+:(?P<key>.+):(?:\s+(?P<value>\S+))?", line) 25 | if match is not None: 26 | # New ':key:' or ':key: value' line, ingest it. 27 | key = match.group("key") 28 | value = match.group("value") or "" 29 | options[key] = value 30 | continue 31 | 32 | # Block is finished, flush it. 33 | in_block_section = False 34 | yield from replace(**options) 35 | yield line 36 | continue 37 | 38 | match = re.search(rf"^::: {title}", line) 39 | if match is not None: 40 | # Block header, ingest it. 41 | in_block_section = True 42 | options = {} 43 | else: 44 | yield line 45 | -------------------------------------------------------------------------------- /mkdocs_typer/_extension.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | from typing import Any, List, Iterator 4 | 5 | from markdown.extensions import Extension 6 | from markdown.preprocessors import Preprocessor 7 | 8 | from ._docs import make_command_docs 9 | from ._exceptions import MkDocsTyperException 10 | from ._loader import load_command 11 | from ._processing import replace_blocks 12 | 13 | 14 | def replace_command_docs(**options: Any) -> Iterator[str]: 15 | for option in ("module", "command"): 16 | if option not in options: 17 | raise MkDocsTyperException(f"Option {option!r} is required") 18 | 19 | module = options["module"] 20 | command = options["command"] 21 | prog_name = options.get("prog_name", command) 22 | depth = int(options.get("depth", 0)) 23 | 24 | command_obj = load_command(module, command) 25 | 26 | return make_command_docs(prog_name=prog_name, command=command_obj, level=depth) 27 | 28 | 29 | class TyperProcessor(Preprocessor): 30 | def run(self, lines: List[str]) -> List[str]: 31 | return list(replace_blocks(lines, title="mkdocs-typer", replace=replace_command_docs)) 32 | 33 | 34 | class MKTyperExtension(Extension): 35 | """ 36 | Replace blocks like the following: 37 | 38 | ::: mkdocs-typer 39 | :module: example.main 40 | :command: app 41 | 42 | by Markdown documentation generated from the specified Typer application. 43 | """ 44 | 45 | def extendMarkdown(self, md: Any) -> None: 46 | md.registerExtension(self) 47 | processor = TyperProcessor(md.parser) 48 | md.preprocessors.register(processor, "mk_typer", 142) 49 | 50 | 51 | def makeExtension() -> Extension: 52 | return MKTyperExtension() 53 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Licensed under the Apache license (see LICENSE) 2 | import re 3 | from pathlib import Path 4 | from setuptools import setup 5 | 6 | 7 | def get_version(package: str) -> str: 8 | text = Path(package, "__version__.py").read_text() 9 | match = re.search('__version__ = "([^"]+)"', text) 10 | assert match is not None 11 | return match.group(1) 12 | 13 | 14 | def get_long_description() -> str: 15 | readme = Path("README.md").read_text() 16 | changelog = Path("CHANGELOG.md").read_text() 17 | return f"{readme}\n\n{changelog}" 18 | 19 | 20 | setup( 21 | name="mkdocs_typer", 22 | version=get_version("mkdocs_typer"), 23 | description="An MkDocs extension to generate documentation for Typer command line applications", 24 | long_description=get_long_description(), 25 | long_description_content_type="text/markdown", 26 | keywords="mkdocs typer", 27 | url="https://github.com/bruce-szalwinski/mkdocs-typer", 28 | author="Bruce Szalwinski", 29 | author_email="bruce.szalwinski@gmail.com", 30 | license="Apache", 31 | packages=["mkdocs_typer"], 32 | install_requires=["typer==0.*", "markdown==3.*"], 33 | python_requires=">=3.7", 34 | include_package_data=True, 35 | zip_safe=False, 36 | entry_points={"markdown.extensions": ["mkdocs-typer = mkdocs_typer:MKTyperExtension"]}, 37 | classifiers=[ 38 | "Development Status :: 4 - Beta", 39 | "Intended Audience :: Developers", 40 | "Operating System :: OS Independent", 41 | "Programming Language :: Python :: 3", 42 | "Programming Language :: Python :: 3.7", 43 | "Programming Language :: Python :: 3.8", 44 | "Programming Language :: Python :: 3.9", 45 | "Programming Language :: Python :: 3.10", 46 | ] 47 | ) 48 | -------------------------------------------------------------------------------- /tests/unit/test_processing.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | from mkdocs_typer._processing import replace_blocks 4 | 5 | 6 | def test_replace_options(): 7 | """Replace a block with options.""" 8 | 9 | source = """ 10 | # Some content 11 | foo 12 | ::: target 13 | :option1: value1 14 | :optiøn2: value2 15 | \t:option3: 16 | :option4:\x20 17 | bar 18 | """.strip() 19 | 20 | expected = """ 21 | # Some content 22 | foo 23 | {'option1': 'value1', 'optiøn2': 'value2', 'option3': '', 'option4': ''} 24 | bar 25 | """.strip() 26 | 27 | output = list(replace_blocks(source.splitlines(), title="target", replace=lambda **options: [str(options)])) 28 | assert output == expected.splitlines() 29 | 30 | 31 | def test_replace_no_options(): 32 | """Replace a block that has no options.""" 33 | 34 | source = """ 35 | # Some content 36 | foo 37 | ::: target 38 | bar 39 | """.strip() 40 | 41 | expected = """ 42 | # Some content 43 | foo 44 | > mock 45 | bar 46 | """.strip() 47 | 48 | output = list(replace_blocks(source.splitlines(), title="target", replace=lambda **options: ["> mock"])) 49 | assert output == expected.splitlines() 50 | 51 | 52 | def test_other_blocks_unchanged(): 53 | """Blocks other than the target block are left unchanged.""" 54 | 55 | source = """ 56 | # Some content 57 | ::: target 58 | ::: plugin1 59 | :option1: value1 60 | ::: target 61 | :option: value 62 | ::: plugin2 63 | :option2: value2 64 | bar 65 | """.strip() 66 | 67 | expected = """ 68 | # Some content 69 | ::: plugin1 70 | :option1: value1 71 | ::: plugin2 72 | :option2: value2 73 | bar 74 | """.strip() 75 | 76 | output = list(replace_blocks(source.splitlines(), title="target", replace=lambda **kwargs: [])) 77 | assert output == expected.splitlines() 78 | -------------------------------------------------------------------------------- /tests/test_extension.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | from pathlib import Path 4 | from textwrap import dedent 5 | 6 | import pytest 7 | from markdown import Markdown 8 | 9 | import mkdocs_typer 10 | 11 | EXPECTED = (Path(__file__).parent / "app" / "expected.md").read_text() 12 | 13 | 14 | def test_extension(): 15 | """ 16 | Markdown output for a relatively complex Typer application is correct. 17 | """ 18 | md = Markdown(extensions=[mkdocs_typer.makeExtension()]) 19 | 20 | source = dedent( 21 | """ 22 | ::: mkdocs-typer 23 | :module: tests.app.cli 24 | :command: my_app 25 | """ 26 | ) 27 | 28 | assert md.convert(source) == md.convert(EXPECTED) 29 | 30 | 31 | def test_prog_name(): 32 | """ 33 | The :prog_name: attribute determines the name to display for the command. 34 | """ 35 | md = Markdown(extensions=[mkdocs_typer.makeExtension()]) 36 | 37 | source = dedent( 38 | """ 39 | ::: mkdocs-typer 40 | :module: tests.app.cli 41 | :command: my_app 42 | :prog_name: custom 43 | """ 44 | ) 45 | 46 | expected = EXPECTED.replace("# my_app", "# custom") 47 | 48 | assert md.convert(source) == md.convert(expected) 49 | 50 | 51 | def test_depth(): 52 | """ 53 | The :depth: attribute increases the level of headers. 54 | """ 55 | md = Markdown(extensions=[mkdocs_typer.makeExtension()]) 56 | 57 | source = dedent( 58 | """ 59 | # CLI Reference 60 | 61 | ::: mkdocs-typer 62 | :module: tests.app.cli 63 | :command: my_app 64 | :depth: 1 65 | """ 66 | ) 67 | 68 | expected = f"# CLI Reference\n\n{EXPECTED.replace('# ', '## ')}" 69 | 70 | assert md.convert(source) == md.convert(expected) 71 | 72 | 73 | @pytest.mark.parametrize("option", ["module", "command"]) 74 | def test_required_options(option): 75 | """ 76 | The module and command options are required. 77 | """ 78 | md = Markdown(extensions=[mkdocs_typer.makeExtension()]) 79 | 80 | source = dedent( 81 | """ 82 | ::: mkdocs-typer 83 | :module: tests.app.cli 84 | :command: my_app 85 | """ 86 | ) 87 | 88 | source = source.replace(f":{option}:", ":somethingelse:") 89 | 90 | with pytest.raises(mkdocs_typer.MkDocsTyperException): 91 | md.convert(source) 92 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .apyre/ 130 | 131 | # PyCharm 132 | .idea/ 133 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # mkdocs-typer 2 | 3 | ![Tests](https://github.com/bruce-szalwinski/mkdocs-typer/workflows/Tests/badge.svg?branch=main) 4 | ![Python versions](https://img.shields.io/pypi/pyversions/mkdocs-typer.svg) 5 | [![Package version](https://badge.fury.io/py/mkdocs-typer.svg)](https://pypi.org/project/mkdocs-typer) 6 | 7 | An MkDocs extension to generate documentation for Typer command line applications. 8 | 9 | ## Installation 10 | 11 | Install from PyPI: 12 | 13 | ```bash 14 | pip install mkdocs-typer 15 | ``` 16 | 17 | ## Quickstart 18 | 19 | Add `mkdocs-typer` to Markdown extensions in your `mkdocs.yml` configuration: 20 | 21 | ```yaml 22 | site_name: Example 23 | theme: readthedocs 24 | 25 | markdown_extensions: 26 | - mkdocs-typer 27 | ``` 28 | 29 | Add a CLI application, e.g.: 30 | 31 | ```python 32 | # app/cli.py 33 | import typer 34 | 35 | 36 | my_app = typer.Typer() 37 | 38 | 39 | @my_app.command() 40 | def foo(): 41 | """do something fooey""" 42 | 43 | 44 | @my_app.callback() 45 | def cli(): 46 | """ 47 | Main entrypoint for this dummy program 48 | """ 49 | ``` 50 | 51 | Add a `mkdocs-typer` block in your Markdown: 52 | 53 | ```markdown 54 | # CLI Reference 55 | 56 | This page provides documentation for our command line tools. 57 | 58 | ::: mkdocs-typer 59 | :module: app.cli 60 | :command: cli 61 | ``` 62 | 63 | Start the docs server: 64 | 65 | ```bash 66 | mkdocs serve 67 | ``` 68 | 69 | Tada! 💫 70 | 71 | ![](https://raw.githubusercontent.com/bruce-szalwinski/mkdocs-typer/master/docs/example.png) 72 | 73 | ## Usage 74 | 75 | ### Documenting commands 76 | 77 | To add documentation for a command, add a `mkdocs-typer` block where the documentation should be inserted. 78 | 79 | Example: 80 | 81 | ```markdown 82 | ::: mkdocs-typer 83 | :module: app.cli 84 | :command: main 85 | ``` 86 | 87 | For all available options, see the [Block syntax](#block-syntax). 88 | 89 | ### Multi-command support 90 | 91 | When pointed at a group (or any other multi-command), `mkdocs-typer` will also generate documentation for sub-commands. 92 | 93 | This allows you to generate documentation for an entire CLI application by pointing `mkdocs-typer` at the root command. 94 | 95 | ### Tweaking header levels 96 | 97 | By default, `mkdocs-typer` generates Markdown headers starting at `<h1>` for the root command section. This is generally what you want when the documentation should fill the entire page. 98 | 99 | If you are inserting documentation within other Markdown content, you can set the `:depth:` option to tweak the initial header level. Note that this applies even if you are just adding a heading. 100 | 101 | By default it is set to `0`, i.e. headers start at `<h1>`. If set to `1`, headers will start at `<h2>`, and so on. Note that if you insert your own first level heading and leave depth at its default value of 0, the page will have multiple `<h1>` tags, which is not compatible with themes that generate page-internal menus such as the ReadTheDocs and mkdocs-material themes. 102 | 103 | ## Reference 104 | 105 | ### Block syntax 106 | 107 | The syntax for `mkdocs-typer` blocks is the following: 108 | 109 | ```markdown 110 | ::: mkdocs-typer 111 | :module: <MODULE> 112 | :command: <COMMAND> 113 | :prog_name: <PROG_NAME> 114 | :depth: <DEPTH> 115 | ``` 116 | 117 | Options: 118 | 119 | - `module`: path to the module where the command object is located. 120 | - `command`: name of the command object. 121 | - `prog_name`: _(Optional, default: same as `command`)_ the name to display for the command. 122 | - `depth`: _(Optional, default: `0`)_ Offset to add when generating headers. 123 | -------------------------------------------------------------------------------- /mkdocs_typer/_docs.py: -------------------------------------------------------------------------------- 1 | # All rights reserved 2 | # Licensed under the Apache license (see LICENSE) 3 | from typing import Iterator, List, Optional 4 | 5 | import typer 6 | import click 7 | from typer.main import get_command 8 | 9 | from ._exceptions import MkDocsTyperException 10 | 11 | 12 | def make_command_docs(prog_name: str, command: typer.main.Typer, level: int = 0) -> Iterator[str]: 13 | """Create the Markdown lines for a command and its sub-commands.""" 14 | cmd = get_command(command) 15 | for line in _recursively_make_command_docs(prog_name, cmd, level=level): 16 | yield line.replace("\b", "") 17 | 18 | 19 | def _recursively_make_command_docs( 20 | prog_name: Optional[str], command: click.Command, parent: typer.Context = None, level: int = 0 21 | ) -> Iterator[str]: 22 | """Create the raw Markdown lines for a command and its sub-commands.""" 23 | ctx = typer.Context(command, parent=parent) 24 | 25 | yield from _make_title(prog_name, level) 26 | yield from _make_description(ctx) 27 | yield from _make_usage(ctx) 28 | yield from _make_options(ctx) 29 | 30 | subcommands = _get_sub_commands(ctx.command, ctx) 31 | 32 | for command in sorted(subcommands, key=lambda cmd: cmd.name if cmd.name else ""): 33 | yield from _recursively_make_command_docs(command.name, command, parent=ctx, level=level + 1) 34 | 35 | 36 | def _get_sub_commands(command: click.Command, ctx: typer.Context) -> List[click.Command]: 37 | """Return subcommands of a Typer command.""" 38 | subcommands = getattr(command, "commands", {}) 39 | if subcommands: 40 | return list(subcommands.values()) 41 | else: 42 | # MultiCommand not created by Typer. 43 | # See https://github.com/DataDog/mkdocs-click/blob/master/mkdocs_click/_docs.py#L45 44 | 45 | return [] 46 | 47 | 48 | def _make_title(prog_name: Optional[str], level: int) -> Iterator[str]: 49 | """Create the first markdown lines describing a command.""" 50 | yield _make_header(prog_name, level) 51 | yield "" 52 | 53 | 54 | def _make_header(text: Optional[str], level: int) -> str: 55 | """Create a markdown header at a given level""" 56 | return f"{'#' * (level + 1)} {text}" 57 | 58 | 59 | def _make_description(ctx: click.Context) -> Iterator[str]: 60 | """Create markdown lines based on the command's own description.""" 61 | help_string = ctx.command.help or ctx.command.short_help 62 | 63 | if help_string: 64 | yield from help_string.splitlines() 65 | yield "" 66 | 67 | 68 | def _make_usage(ctx: click.Context) -> Iterator[str]: 69 | """Create the Markdown lines from the command usage string.""" 70 | 71 | # Gets the usual 'Usage' string without the prefix. 72 | formatter = ctx.make_formatter() 73 | pieces = ctx.command.collect_usage_pieces(ctx) 74 | formatter.write_usage(ctx.command_path, " ".join(pieces), prefix="") 75 | usage = formatter.getvalue().rstrip("\n") 76 | 77 | # Generate the full usage string based on parents if any, i.e. `root sub1 sub2 ...`. 78 | full_path = [] 79 | current: Optional[click.Context] = ctx 80 | while current is not None: 81 | name = current.command.name 82 | if name is None: 83 | raise MkDocsTyperException(f"command {current.command} has no `name`") 84 | full_path.append(name) 85 | current = current.parent 86 | 87 | full_path.reverse() 88 | usage_snippet = " ".join(full_path) + usage 89 | 90 | yield "Usage:" 91 | yield "" 92 | yield "```" 93 | yield usage_snippet 94 | yield "```" 95 | yield "" 96 | 97 | 98 | def _make_options(ctx: typer.Context) -> Iterator[str]: 99 | """Create the Markdown lines describing the options for the command.""" 100 | formatter = ctx.make_formatter() 101 | click.Command.format_options(ctx.command, ctx, formatter) 102 | # First line is redundant "Options" 103 | # Last line is `--help` 104 | option_lines = formatter.getvalue().splitlines()[1:-1] 105 | if not option_lines: 106 | return 107 | 108 | yield "Options:" 109 | yield "" 110 | yield "```" 111 | yield from option_lines 112 | yield "```" 113 | yield "" 114 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------