|
| 1 | +""" |
| 2 | +This script can be used to automatically generate a table of contents (JSON file) from the markdown files in a directory, |
| 3 | +or multiple directories. |
| 4 | +""" |
| 5 | + |
| 6 | +#!/usr/bin/env python3 |
| 7 | + |
| 8 | +import json |
| 9 | +import os |
| 10 | +import argparse |
| 11 | +import sys |
| 12 | + |
| 13 | +def parse_args() -> argparse.Namespace: |
| 14 | + parser = argparse.ArgumentParser( |
| 15 | + formatter_class=argparse.ArgumentDefaultsHelpFormatter, |
| 16 | + description="Script to generate .json table of contents from YAML frontmatter title, description and slug", |
| 17 | + ) |
| 18 | + parser.add_argument( |
| 19 | + "--single-toc", |
| 20 | + action="store_true", |
| 21 | + help="Generates a single TOC for all files in all sub-directories of provided directory. By default, generates TOC per folder.", |
| 22 | + ) |
| 23 | + parser.add_argument( |
| 24 | + "--dir", |
| 25 | + help="Path to a folder containing markdown (.md, .mdx) documents containing YAML with title, description, slug." |
| 26 | + ) |
| 27 | + return parser.parse_args() |
| 28 | + |
| 29 | +def extract_title_description_slug(filename): |
| 30 | + with open(filename, "r") as f: |
| 31 | + lines = f.readlines() |
| 32 | + |
| 33 | + title, description, slug = None, None, None |
| 34 | + for line in lines: |
| 35 | + if line.startswith("title:"): |
| 36 | + title = line.strip().split(": ")[1] |
| 37 | + if line.startswith("description:"): |
| 38 | + description = line.strip().split(": ")[1] |
| 39 | + elif line.startswith("slug:"): |
| 40 | + slug = line.strip().split(": ")[1] |
| 41 | + if title and slug and description: |
| 42 | + return {"title": title, "description": description, "slug": slug} |
| 43 | + return None |
| 44 | + |
| 45 | +def walk_dirs(root_dir): |
| 46 | + for root, dirs, files in os.walk(root_dir): |
| 47 | + yield root |
| 48 | + |
| 49 | +def write_to_file(json_array, output_path): |
| 50 | + try: |
| 51 | + os.makedirs(os.path.dirname(output_path), exist_ok=True) # Create directories if they don't exist |
| 52 | + with open(output_path, "w") as f: |
| 53 | + json.dump(json_array, f, indent=4) |
| 54 | + f.write('\n') |
| 55 | + except OSError as e: |
| 56 | + if e.errno == 21: |
| 57 | + print(f"Directory already exists: {e}") |
| 58 | + else: |
| 59 | + print(f"An error occurred creating directory: {e}") |
| 60 | + |
| 61 | +def main(): |
| 62 | + |
| 63 | + # Extract script arguments |
| 64 | + args = parse_args() |
| 65 | + root_dir = args.dir |
| 66 | + if root_dir is None: |
| 67 | + print("Please provide a directory with argument --dir") |
| 68 | + sys.exit(1) |
| 69 | + |
| 70 | + if args.single_toc: |
| 71 | + json_items = [] # single list for all directories |
| 72 | + |
| 73 | + for directory in walk_dirs(root_dir): # Walk directories |
| 74 | + |
| 75 | + if not args.single_toc: |
| 76 | + json_items = [] # new list for each directory |
| 77 | + |
| 78 | + for filename in os.listdir(directory): # for each directory |
| 79 | + full_path = os.path.join(directory, filename) |
| 80 | + if os.path.isfile(full_path) is False: |
| 81 | + continue |
| 82 | + else: |
| 83 | + # index.md is ignored as we expect this to be the page for the table of contents |
| 84 | + if (filename.endswith(".md") or filename.endswith(".mdx")) and filename != "index.md": |
| 85 | + result = extract_title_description_slug(full_path) |
| 86 | + if result is not None: |
| 87 | + json_items.append(result) |
| 88 | + |
| 89 | + if not args.single_toc: |
| 90 | + json_array = sorted(json_items, key=lambda x: x.get("title")) |
| 91 | + |
| 92 | + # don't write toc.json for empty folders |
| 93 | + if len(json_items) != 0: |
| 94 | + write_to_file(json_items, directory+"/toc.json") |
| 95 | + |
| 96 | + if args.single_toc: |
| 97 | + json_array = sorted(json_items, key=lambda x: x.get("title")) |
| 98 | + # don't write toc.json for empty folders |
| 99 | + if len(json_items) != 0: |
| 100 | + write_to_file(json_items, root_dir+"/toc.json") |
| 101 | + |
| 102 | +if __name__ == "__main__": |
| 103 | + main() |
| 104 | + |
0 commit comments