formatting.py (1484B)
1 import os 2 import re 3 4 def esc_yaml(s: str) -> str: 5 return s.replace("'", "''") 6 7 def slugify_tag(s: str) -> str: 8 """Turn a folder name into a clean tag slug.""" 9 s = s.strip().lower() 10 s = re.sub(r'[_\s]+', '-', s) 11 s = re.sub(r'[^a-z0-9\-]', '', s) 12 return re.sub(r'-+', '-', s).strip('-') 13 14 def derive_tags(rel_path: str, lang_label: str = "") -> list: 15 """Derive tag slugs from a file path relative to BSC_ROOT.""" 16 parts = [p for p in os.path.normpath(rel_path).split(os.sep) if p] 17 tags = [] 18 19 # 1. Generate tags from folder names 20 for part in parts[:-1]: 21 m = re.match(r'^semester[_-]?(\d+)$', part, re.IGNORECASE) 22 tag = f"sem{m.group(1)}" if m else slugify_tag(part) 23 if tag and tag not in tags: 24 tags.append(tag) 25 26 # 2. Dynamically generate the language tag from the exact file extension 27 _, ext = os.path.splitext(rel_path) 28 if ext: 29 # Removes the '.' and converts to uppercase (e.g., '.cpp' -> 'CPP') 30 ext_tag = ext.lstrip('.').upper() 31 if ext_tag and ext_tag not in tags: 32 tags.append(ext_tag) 33 34 return tags 35 36 def format_tags_yaml(tags: list) -> str: 37 if not tags: 38 return "tags: []" 39 items = ", ".join(f"'{esc_yaml(t)}'" for t in tags) 40 return f"tags: [{items}]" 41 42 def esc_html(s: str) -> str: 43 """Escape characters that break Vue template compilation in VitePress.""" 44 return s.replace('&', '&').replace('<', '<').replace('>', '>')