Updating a Markdown table of contents with a GitHub Action#
markdown-toc is a Node script that parses a Markdown file and generates a table of contents for it, based on the headings.
You can run it (without installing anything first thanks to the magic of npx) like so:
1npx markdown-toc README.md
This will output the table of contents to standard out.
You can add the following comment to a markdown file:
1<!-- toc -->2<!-- tocstop -->
And then run the command like this to update a table of contents in place:
1npx markdown-toc -i README.md
I wrote this GitHub Action to apply this command every time the README is updated, then commit the results back to the repository.
Save this as .github/workflows/readme-toc.yml
:
1name: Update README table of contents2
3on:4 workflow_dispatch:5 push:6 branches:7 - main8 - master9 paths:10 - README.md11
12jobs:13 build:14 runs-on: ubuntu-latest15 steps:16 - name: Check out repo17 uses: actions/checkout@v218 - name: Update TOC19 run: npx markdown-toc README.md -i20 - name: Commit and push if README changed21 run: |-22 git diff23 git config --global user.email "readme-bot@example.com"24 git config --global user.name "README-bot"25 git diff --quiet || (git add README.md && git commit -m "Updated README")26 git push
You can see this running on the dogsheep/twitter-to-sqlite repository.
Unfortunately these links don’t work on READMEs that are rendered by PyPI yet, e.g. twitter-to-sqlite. There’s an open issue for that here.