Add YAML frontmatter tagging system + tag indexes + regeneration script
This commit is contained in:
1 parent
cd7aa0f288
commit
c283cf5955
74 files changed
+897
No files matched your search
@@ -0,0 +1,237 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate tag index pages from YAML frontmatter in wiki markdown files.
|
||||
|
||||
Scans all .md files in the wiki (excluding tags/ and .git/), parses YAML
|
||||
frontmatter, and regenerates tag index pages in tags/ plus a master
|
||||
tags/README.md index.
|
||||
|
||||
Usage:
|
||||
python3 scripts/generate_tag_index.py
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
# Tag dimensions in display order
|
||||
DIMENSIONS = ["type", "function", "region", "maturity", "ownership"]
|
||||
|
||||
|
||||
def parse_frontmatter(content):
|
||||
"""Parse YAML frontmatter from markdown content. Returns (frontmatter_dict, body)."""
|
||||
if not content.startswith("---\n"):
|
||||
return {}, content
|
||||
|
||||
parts = content.split("---\n", 2)
|
||||
if len(parts) < 3:
|
||||
return {}, content
|
||||
|
||||
fm_text = parts[1]
|
||||
body = parts[2]
|
||||
fm = {}
|
||||
for line in fm_text.strip().split("\n"):
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
if ":" in line:
|
||||
key, value = line.split(":", 1)
|
||||
fm[key.strip()] = value.strip()
|
||||
|
||||
return fm, body
|
||||
|
||||
|
||||
def add_frontmatter(filepath, tags):
|
||||
"""Add or update YAML frontmatter on a markdown file."""
|
||||
with open(filepath, "r") as f:
|
||||
content = f.read()
|
||||
|
||||
fm, body = parse_frontmatter(content)
|
||||
|
||||
# Merge: existing values take precedence (don't overwrite manually edited tags)
|
||||
for key, value in tags.items():
|
||||
if key not in fm:
|
||||
fm[key] = value
|
||||
|
||||
# Build new frontmatter
|
||||
fm_lines = ["---"]
|
||||
for dim in DIMENSIONS:
|
||||
if dim in fm:
|
||||
fm_lines.append(f"{dim}: {fm[dim]}")
|
||||
# Include any extra keys not in DIMENSIONS
|
||||
for key, value in fm.items():
|
||||
if key not in DIMENSIONS:
|
||||
fm_lines.append(f"{key}: {value}")
|
||||
fm_lines.append("---")
|
||||
fm_lines.append("")
|
||||
|
||||
new_content = "\n".join(fm_lines) + body
|
||||
with open(filepath, "w") as f:
|
||||
f.write(new_content)
|
||||
|
||||
|
||||
def extract_title_and_description(content):
|
||||
"""Extract the H1 title and a one-line description from markdown body."""
|
||||
title = ""
|
||||
desc = ""
|
||||
|
||||
lines = content.split("\n")
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("# ") and not title:
|
||||
title = stripped[2:].strip()
|
||||
continue
|
||||
if not title:
|
||||
continue
|
||||
# Skip blank lines, metadata fields, horizontal rules, and list items
|
||||
if (
|
||||
stripped
|
||||
and not stripped.startswith("**")
|
||||
and not stripped.startswith("---")
|
||||
and not stripped.startswith("#")
|
||||
and not stripped.startswith("-")
|
||||
):
|
||||
# Truncate at sentence boundary or 120 chars
|
||||
desc = stripped
|
||||
if len(desc) > 120:
|
||||
# Try to cut at a sentence boundary
|
||||
for i, ch in enumerate(desc):
|
||||
if ch in ".!?" and i > 40:
|
||||
desc = desc[: i + 1]
|
||||
break
|
||||
else:
|
||||
desc = desc[:117] + "..."
|
||||
break
|
||||
|
||||
return title, desc
|
||||
|
||||
|
||||
def scan_wiki(wiki_root):
|
||||
"""Scan all .md files in the wiki, returning list of (relpath, frontmatter, title, description)."""
|
||||
pages = []
|
||||
for root, dirs, files in os.walk(wiki_root):
|
||||
# Skip .git and tags directories
|
||||
if ".git" in root or os.path.join("tags") in os.path.relpath(root, wiki_root):
|
||||
continue
|
||||
for fname in sorted(files):
|
||||
if not fname.endswith(".md"):
|
||||
continue
|
||||
fpath = os.path.join(root, fname)
|
||||
relpath = os.path.relpath(fpath, wiki_root)
|
||||
with open(fpath, "r") as f:
|
||||
content = f.read()
|
||||
fm, body = parse_frontmatter(content)
|
||||
title, desc = extract_title_and_description(body)
|
||||
pages.append((relpath, fm, title, desc))
|
||||
return pages
|
||||
|
||||
|
||||
def sanitize_filename(value):
|
||||
"""Sanitize a tag value for use in a filename."""
|
||||
return value.replace("/", "-").replace(" ", "-")
|
||||
|
||||
|
||||
def generate_tag_indexes(wiki_root):
|
||||
"""Generate all tag index pages and the master index."""
|
||||
pages = scan_wiki(wiki_root)
|
||||
|
||||
# Build tag -> pages mapping
|
||||
# tag_key is "dim-value" (raw), filename_key is sanitized for filesystem
|
||||
tag_pages = defaultdict(list) # filename_key -> [(relpath, title, desc)]
|
||||
tag_info = {} # filename_key -> (dim, value) for display
|
||||
for relpath, fm, title, desc in pages:
|
||||
for dim in DIMENSIONS:
|
||||
if dim in fm and fm[dim]:
|
||||
value = fm[dim]
|
||||
filename_key = f"{dim}-{sanitize_filename(value)}"
|
||||
tag_pages[filename_key].append((relpath, title, desc))
|
||||
tag_info[filename_key] = (dim, value)
|
||||
|
||||
tags_dir = os.path.join(wiki_root, "tags")
|
||||
os.makedirs(tags_dir, exist_ok=True)
|
||||
|
||||
# Generate individual tag pages
|
||||
for filename_key in sorted(tag_pages.keys()):
|
||||
page_list = tag_pages[filename_key]
|
||||
# Sort by title
|
||||
page_list.sort(key=lambda x: x[1].lower())
|
||||
|
||||
dim, value = tag_info[filename_key]
|
||||
|
||||
lines = [f"# Tag: {value}", ""]
|
||||
lines.append(f"Pages tagged `{dim}: {value}`:")
|
||||
lines.append("")
|
||||
for relpath, title, desc in page_list:
|
||||
# Calculate relative link from tags/ to the page
|
||||
link = os.path.relpath(os.path.join(wiki_root, relpath), tags_dir)
|
||||
desc_text = f" — {desc}" if desc else ""
|
||||
lines.append(f"- [{title}]({link}){desc_text}")
|
||||
lines.append("")
|
||||
|
||||
tag_file = os.path.join(tags_dir, f"tag-{filename_key}.md")
|
||||
with open(tag_file, "w") as f:
|
||||
f.write("\n".join(lines))
|
||||
|
||||
# Generate master index (tags/README.md)
|
||||
lines = ["# Tag Index", ""]
|
||||
lines.append("All tags in the wiki, grouped by dimension. Click through to see all pages with that tag.")
|
||||
lines.append("")
|
||||
|
||||
# Group tags by dimension
|
||||
tags_by_dim = defaultdict(list) # dim -> [(value, filename_key)]
|
||||
for filename_key in tag_pages:
|
||||
dim, value = tag_info[filename_key]
|
||||
tags_by_dim[dim].append((value, filename_key))
|
||||
|
||||
for dim in DIMENSIONS:
|
||||
if dim not in tags_by_dim:
|
||||
continue
|
||||
lines.append(f"## {dim.capitalize()}")
|
||||
lines.append("")
|
||||
for value, filename_key in sorted(tags_by_dim[dim], key=lambda x: x[0].lower()):
|
||||
count = len(tag_pages[filename_key])
|
||||
lines.append(f"- [{value}](tag-{filename_key}.md) ({count})")
|
||||
lines.append("")
|
||||
|
||||
# Also list by dimension with backlinks to pages
|
||||
lines.append("---")
|
||||
lines.append("")
|
||||
lines.append("## Regeneration")
|
||||
lines.append("")
|
||||
lines.append("Tag indexes are auto-generated from YAML frontmatter in wiki markdown files.")
|
||||
lines.append("")
|
||||
lines.append("```bash")
|
||||
lines.append("python3 scripts/generate_tag_index.py")
|
||||
lines.append("```")
|
||||
lines.append("")
|
||||
|
||||
readme_file = os.path.join(tags_dir, "README.md")
|
||||
with open(readme_file, "w") as f:
|
||||
f.write("\n".join(lines))
|
||||
|
||||
# Clean up stale tag files
|
||||
expected_files = {f"tag-{tk}.md" for tk in tag_pages} | {"README.md"}
|
||||
for fname in os.listdir(tags_dir):
|
||||
if fname.endswith(".md") and fname not in expected_files:
|
||||
os.remove(os.path.join(tags_dir, fname))
|
||||
|
||||
print(f"Generated {len(tag_pages)} tag index pages in tags/")
|
||||
print(f"Master index: tags/README.md")
|
||||
for dim in DIMENSIONS:
|
||||
if dim in tags_by_dim:
|
||||
print(f" {dim}: {len(tags_by_dim[dim])} tags")
|
||||
|
||||
|
||||
def main():
|
||||
# Wiki root is the parent of the scripts/ directory
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
wiki_root = os.path.dirname(script_dir)
|
||||
|
||||
if not os.path.isdir(os.path.join(wiki_root, ".git")):
|
||||
print(f"Warning: {wiki_root} does not appear to be a git repo", file=sys.stderr)
|
||||
|
||||
generate_tag_indexes(wiki_root)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user