70 lines
2.1 KiB
Python
70 lines
2.1 KiB
Python
#!/usr/bin/env python3
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import re
|
|
from pathlib import Path
|
|
|
|
|
|
CAMEL_CASE_RE = re.compile(r'(?<=[a-z])(?=[A-Z])')
|
|
MARKDOWN_LINK_RE = re.compile(r'^\[(.*?)\]\([^)]*\)$')
|
|
|
|
|
|
def read_title(markdown_path: Path) -> str:
|
|
for line in markdown_path.read_text(encoding='utf-8').splitlines():
|
|
if line.startswith('# '):
|
|
title = line[2:].strip()
|
|
link_match = MARKDOWN_LINK_RE.match(title)
|
|
return link_match.group(1) if link_match else title
|
|
return markdown_path.stem
|
|
|
|
|
|
def humanize_token(token: str) -> str:
|
|
return CAMEL_CASE_RE.sub(' ', token).strip()
|
|
|
|
|
|
def display_section_name(directory_name: str) -> str:
|
|
parts = [humanize_token(part) for part in directory_name.split('_') if part]
|
|
if not parts:
|
|
return directory_name
|
|
if len(parts) == 1:
|
|
return parts[0]
|
|
if len(parts) == 2:
|
|
return f'{parts[0]} & {parts[1]}'
|
|
return f"{', '.join(parts[:-1])} & {parts[-1]}"
|
|
|
|
|
|
def build_index(workshops_dir: Path) -> str:
|
|
sections: list[str] = ['# Workshops Index']
|
|
|
|
for subdir in sorted(path for path in workshops_dir.iterdir() if path.is_dir()):
|
|
sections.append(f'## {display_section_name(subdir.name)}')
|
|
|
|
markdown_files = sorted(subdir.glob('*.md'))
|
|
if not markdown_files:
|
|
sections.append('_No Markdown files found._')
|
|
continue
|
|
|
|
for markdown_file in markdown_files:
|
|
title = read_title(markdown_file)
|
|
relative_path = markdown_file.relative_to(workshops_dir)
|
|
sections.append(f'- [{title}]({relative_path.as_posix()})')
|
|
|
|
sections.append('')
|
|
|
|
return '\n'.join(sections).rstrip() + '\n'
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description='Generate a Markdown index for workshop subdirectories.')
|
|
parser.add_argument('directory', type=Path, help='Workshops directory containing topic subdirectories')
|
|
args = parser.parse_args()
|
|
|
|
index_path = args.directory / 'index.md'
|
|
index_path.write_text(build_index(args.directory), encoding='utf-8')
|
|
print(index_path)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main() |