Easily generate a markdown Table of Contents (TOC) for your GitHub repository. Automatically respects .gitignore files and excludes ignored files and directories from the TOC.
Install the package using npm:
npm install -g repo-tocrepo-toc provides a simple way to generate a markdown Table of Contents for all files in your GitHub repository.
Your directory structure:
.
├── TestFile3.md
├── test-files/
│ ├── TestFile1.md
│ └── TextFile.txt
The generated Table of Contents:
<!---TOC-START--->
* [TestFile3](./TestFile3.md)
* **test-files**
* [Test File 1 Title](./test-files/TestFile1.md)
<!---TOC-END--->repo-toc [options]
Options:
--version Show version number [boolean]
-d, --dir Directory path to generate TOC for
[string] [default: process.cwd()]
-e, --ext File extensions to include (comma-separated)
[string] [default: ".md"]
-o, --output File path to save the TOC [string] [default: "./README.md"]
-x, --exclude Directories to exclude (comma-separated) [string]
-h, --help Show help [boolean]
**Important**: Files and directories listed in `.gitignore` files are automatically excluded from the TOC generation. This includes:
- Files and directories specified in `.gitignore` at any level in your repository
- Common ignored patterns like `node_modules/`, `dist/`, `build/`, `.git/`, etc.
- You can still use the `--exclude` option to exclude additional directories beyond what's in `.gitignore`repo-toc
repo-toc automatically respects .gitignore files throughout your repository:
- Automatic exclusion: Files and directories listed in
.gitignoreare automatically excluded from TOC generation - Multi-level support: Respects
.gitignorefiles at any directory level in your repository - Common patterns: Automatically excludes common ignored patterns like
node_modules/,dist/,build/,.git/, etc. - Additional exclusions: You can still use the
--excludeoption to exclude additional directories beyond what's in.gitignore
This ensures your TOC only includes files that are actually tracked in your repository, keeping it clean and relevant.
Generate TOC excluding specific directories:
repo-toc --exclude node_modules,dist,buildGenerate TOC for only JavaScript files, excluding test directories:
repo-toc --ext .js,.ts --exclude tests,__tests__,specNote: The tool automatically respects .gitignore files and excludes any files or directories listed there, in addition to your manual exclusions. This ensures your TOC only includes files that are actually tracked in your repository.
You can integrate repo-toc with pre-commit hooks to automatically generate and update the TOC before each commit. This ensures your TOC is always up-to-date.
- Install pre-commit (if not already installed):
pip install pre-commit- Add repo-toc to your package.json:
{
"devDependencies": {
"repo-toc": "^1.2.0"
},
"scripts": {
"generate-toc": "./.github/hooks/generate-toc.sh",
"install-hooks": "pre-commit install"
}
}- Create a pre-commit hook script (
.github/hooks/generate-toc.sh):
#!/bin/bash
set -e
echo "🔄 Generating Table of Contents..."
# Check if Node.js and npm are available
if ! command -v node &> /dev/null || ! command -v npm &> /dev/null; then
echo "❌ Node.js/npm is not installed. Please install Node.js to generate TOC."
exit 1
fi
# Install repo-toc if not already installed
if ! npm list -g repo-toc &> /dev/null; then
echo "📦 Installing repo-toc globally..."
npm install -g repo-toc
fi
# Generate TOC for README.md
if [ -f "README.md" ]; then
echo "📝 Updating Table of Contents in README.md..."
# Create a backup
cp README.md README.md.backup
# Generate TOC with repo-toc
repo-toc -i README.md
# Check if the file was modified
if ! cmp -s README.md README.md.backup; then
echo "✅ Table of Contents updated successfully!"
# Add the updated file to git staging area
git add README.md
else
echo "ℹ️ Table of Contents is already up to date."
fi
# Clean up backup
rm README.md.backup
else
echo "❌ README.md not found in current directory"
exit 1
fi
echo "🎉 TOC generation completed!"- Configure pre-commit (
.pre-commit-config.yaml):
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-markdown
args: [--fix]
- repo: local
hooks:
- id: generate-toc
name: Generate Table of Contents
entry: ./.github/hooks/generate-toc.sh
language: script
files: '^README\.md$'
pass_filenames: false
stages: [commit]
- repo: https://github.com/igorshubovych/markdownlint-cli
rev: v0.37.0
hooks:
- id: markdownlint
args: [--fix]
files: \.md$- Install the pre-commit hooks:
npm run install-hooks
# or
pre-commit install- Automatic TOC updates: TOC is generated/updated automatically before each commit
- Consistent formatting: Ensures TOC follows the same format across all commits
- No manual intervention: Developers don't need to remember to update the TOC
- Integration with other hooks: Works seamlessly with markdown linting and other pre-commit hooks
It will auto generate the TOC after you commit things on Github. You use this github action
name: Generate TOC
on:
push:
branches:
- main
jobs:
toc:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install markdown-toc
run: npm install -g repo-toc
- name: Generate TOC
run: repo-toc -i README.md
- name: Commit and Push Changes
run: |
git config --global user.name "github-actions[bot]"
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git add README.md
git commit -m "Update TOC"
git push
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}To generate the TOC:
const path = require('path');
const dirPath = path.join(__dirname, "mocks");
const filePath = path.join(__dirname, "README.md");
fs.writeFileSync(filePath, "## Table of contents");
generateTableOfContent({ dirPath, filePath });
// Generate TOC excluding specific directories
// Note: .gitignore files are automatically respected
generateTableOfContent({
dirPath: __dirname,
filePath: path.join(__dirname, "README.md"),
excludedDirs: ["node_modules", "dist", "build"]
});
// Call the function to generate the TOC
generateTableOfContent();
// It will update the README.md file with the Table of ContentsGenerates a Table of Contents for the specified directory.
options(object): Configuration options for generating the TOC.dirPath(string): The directory path to scan for files.- Default:
process.cwd()(the current working directory).
- Default:
extensions(array of strings): An array of file extensions to include in the TOC.- Default:
[".md"].
- Default:
filePath(string): The path where the generated TOC will be written.- Default:
path.join(__dirname, "README.md").
- Default:
excludedDirs(array of strings): An array of directory names to exclude from the TOC.- Default:
[]. - Automatic exclusions: Directories starting with
.and files/directories listed in.gitignorefiles are automatically excluded, regardless of this parameter. - This parameter allows you to exclude additional directories beyond what's already ignored by
.gitignore.
- Default:
Returns:
void
We welcome contributions! If you'd like to report issues, request features, or submit pull requests, please visit our GitHub repository.
This package uses automated publishing to NPM:
- Automatic: New versions are published automatically when changes are merged to the main branch
- Version Bumping: Semantic versioning based on conventional commit messages
- Release Notes: GitHub releases are created automatically with each publish
For setup details, see Release Setup Guide.
This package is licensed under the ISC License.
Feel free to customize this further based on additional features or specific instructions.