Posts /

Insert Table of Content using Github Actions

24 Dec 2022

Insert a table of contents (TOC) into a README.md file using GitHub Actions, you need to set up a GitHub Action to update the TOC in your README.md file. This is a quick and easy way to keep your TOC up-to-date without having to do it manually.

Table of Content

How to Insert a Table of Contents into a README.md File using GitHub Actions

Are you tired of manually updating the table of contents (TOC) in your README.md file every time you make changes to your repository? Do you want an automated way to keep your TOC up-to-date? If so, then using GitHub Actions is the way to go!

Prerequisites

Before we get started, make sure you have the following:

Step 1: Update you README.md file to allow TOC

To automatically add update TOC on each update to your README.md file. You need to first add the following lines in your README.md file where you want your TOC to go.

<!--ts-->
<!--te-->

Step 2: Commit and Push the Changes

To save the changes to your README.md file, you will need to commit and push them to your repository. Run the following commands:

git add README.md
git commit -m "Auto-insert TOC anchors added to README.md"
git push

This will commit and push the changes to your repository.

Step 3: Set Up a GitHub Action

To automate the process of updating the TOC in your README.md file, you can set up a GitHub Action. In your repository, go to the Actions tab and click on the New workflow button.

Then, create a new file called insert-toc.yaml in the .github/workflows directory and add the following code:

name: Insert TOC

on:
  push:
    branches: [main]
    paths: ['README.md']

  workflow_dispatch:


jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - uses: actions/checkout@v2
      - run: |
          curl https://raw.githubusercontent.com/ekalinin/github-markdown-toc/0.8.0/gh-md-toc -o gh-md-toc
          chmod a+x gh-md-toc
          ./gh-md-toc --insert --no-backup --hide-footer README.md
          rm gh-md-toc
      - uses: stefanzweifel/git-auto-commit-action@v4
        with:
          commit_message: Auto update markdown TOC

This action will run every time you push changes to README.md file in the main branch of your repository and will automatically update the TOC in your README.md file.

Conclusion

Using GitHub Actions to automatically update the TOC in your README.md file is a quick and easy way to keep your TOC up-to-date without having to do it manually. Give it a try and see how it can streamline you workflow.