|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import os |
| 3 | +import re |
| 4 | + |
| 5 | +# This script migrates all existing device files in _oem/ |
| 6 | +# from old permalink structure to new dual-link structure. |
| 7 | +# It forces the vendor part of the URL to be LOWERCASE. |
| 8 | +# Old: permalink: /codename/ |
| 9 | +# New: permalink: /codename/ |
| 10 | +# redirect_from: /devices/lower_vendor/codename/ |
| 11 | + |
| 12 | +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 13 | +OEM_DIR = os.path.join(REPO_ROOT, "_oem") |
| 14 | + |
| 15 | +def fix_file(file_path, vendor): |
| 16 | + with open(file_path, 'r', encoding='utf-8') as f: |
| 17 | + content = f.read() |
| 18 | + |
| 19 | + # Regex to find codename |
| 20 | + codename_match = re.search(r'^codename:\s*(.+)$', content, re.MULTILINE) |
| 21 | + if not codename_match: |
| 22 | + print(f"Skipping {file_path}: No codename found") |
| 23 | + return |
| 24 | + |
| 25 | + codename = codename_match.group(1).strip() |
| 26 | + |
| 27 | + # Construct desired lines (Force vendor to lowercase for URL) |
| 28 | + vendor_slug = vendor.lower() |
| 29 | + new_permalink = f"permalink: /{codename}/" |
| 30 | + new_redirect = f"redirect_from: /devices/{vendor_slug}/{codename}/" |
| 31 | + |
| 32 | + # Check if already updated |
| 33 | + if new_permalink in content and new_redirect in content: |
| 34 | + return |
| 35 | + |
| 36 | + # Replace old permalink |
| 37 | + # Case 1: permalink exists |
| 38 | + permalink_pattern = re.compile(r'^permalink:.*$', re.MULTILINE) |
| 39 | + |
| 40 | + if permalink_pattern.search(content): |
| 41 | + # Replace existing permalink |
| 42 | + content = permalink_pattern.sub(new_permalink + "\n" + new_redirect, content) |
| 43 | + print(f"Updated {vendor}/{codename}") |
| 44 | + else: |
| 45 | + # Case 2: permalink might be missing (using default), add it after codename |
| 46 | + content = content.replace(f"codename: {codename}", f"codename: {codename}\n{new_permalink}\n{new_redirect}") |
| 47 | + print(f"Added permalink to {vendor}/{codename}") |
| 48 | + |
| 49 | + with open(file_path, 'w', encoding='utf-8') as f: |
| 50 | + f.write(content) |
| 51 | + |
| 52 | +def main(): |
| 53 | + print("Starting Permalink Migration...") |
| 54 | + if not os.path.exists(OEM_DIR): |
| 55 | + print(f"Error: {OEM_DIR} not found.") |
| 56 | + return |
| 57 | + |
| 58 | + count = 0 |
| 59 | + for root, dirs, files in os.walk(OEM_DIR): |
| 60 | + for file in files: |
| 61 | + if file.endswith(".md"): |
| 62 | + # Get vendor from directory name |
| 63 | + vendor = os.path.basename(root) |
| 64 | + fix_file(os.path.join(root, file), vendor) |
| 65 | + count += 1 |
| 66 | + |
| 67 | + print(f"Processed {count} files.") |
| 68 | + |
| 69 | +if __name__ == "__main__": |
| 70 | + main() |
0 commit comments