Add a github action to generate documentation using mkdocs

python mkdocs github action

3 min read | by Jordi Prats

If you have a tool that uses the python's click module for building a command line interface. Using mkdocs and mkdocs-click we can automatically generate documentation for it

First we will have to install mkdocs and mkdocs-click using pip as follows:

pip install mkdocs
pip install mkdocs-click

Using awstools as an example, we'll have to create the following files:

First, the general configuration (/mkdocs.yml)

site_name: awstools
theme: 
    name: readthedocs
    navigation_depth: 8
    nav_style: dark
    collapse_navigation: False

docs_dir: docs

markdown_extensions:
    - mkdocs-click

To generate pages, we'll need to create the markdown pages that we need. The index page it's going to be (/docs/index.md). For this example we are going to use it to directly hold the documentation we want to generate:

# CLI Reference

This page provides documentation for our command line tools.

::: mkdocs-click
    :module: awstools
    :command: awstools
    :depth: 4
    :style: table

We can test it running mkdocs serve, it will listen to 127.0.0.1:8000 so we can see how it will look like:

$ PYTHONPATH=$PWD mkdocs serve
INFO     -  Building documentation...
INFO     -  Cleaning site directory
INFO     -  Documentation built in 0.53 seconds
INFO     -  [19:28:44] Watching paths for changes: 'docs', 'mkdocs.yml'
INFO     -  [19:28:44] Serving on http://127.0.0.1:8000/
(...)

Finally, we can create github action (/.github/workflows/docs.yaml)to automatically update the documentation on each push to master. We are going to use Github pages for this:

name: build
on:
  push:
    branches:
      - main
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-python@v2
        with:
          python-version: 3.x
      - run: pip install mkdocs
      - run: pip install mkdocs-click
      - run: pip install -r requirements.txt
      - run: export PYTHONPATH=$(pwd)
      - run: bash -c "PYTHONPATH=$PWD mkdocs gh-deploy --force --clean --verbose"

As soon as this action completes, if we have the github pages enabled (check Settings, Pages) we will be able to reach the documentation using an URL based on:



https://username.github.io/reponame/



For example, for the awstools repo belonging to jordiprats it is going to be:

https://jordiprats.github.io/awstools/

You can use this commit belonging to the python-matecurses project as an example since it contains all the changes needed for this.


Posted on 14/06/2022

Categories