Files
dbis_docs/scripts/fix_root_references.py

148 lines
5.0 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
"""
Script to fix references from subdirectories to root-level files.
Adds ../ prefix where needed for files in subdirectories.
"""
import os
import re
from pathlib import Path
# Root-level files that might be referenced
ROOT_FILES = [
'MASTER_INDEX.md',
'QUICK_REFERENCE.md',
'DOCUMENT_RELATIONSHIP_MAP.md',
'GLOSSARY.md',
'VERSION_CONTROL_POLICY.md',
'EXECUTIVE_SUMMARY.md',
'TIMELINE_VISUALIZATION.md',
'QUALITY_VERIFICATION_REPORT.md',
'RECOMMENDATIONS_AND_SUGGESTIONS.md',
'GRADING_AND_SCORING_REPORT.md',
'CROSS_REFERENCE_VERIFICATION_REPORT.md',
'IMMEDIATE_NEXT_STEPS.md',
'Template_System_Requirements.md',
'RESOURCE_REQUIREMENTS_SUMMARY.md',
'README.md',
'NAVIGATION_GUIDE.md',
]
# Directory references that need fixing
DIR_REFS = [
'QUICK_START_GUIDES/',
'00_document_control/',
'01_constitutional/',
'02_statutory_code/',
'03_governance/',
'04_legal_regulatory/',
'05_financial_reserve/',
'06_cyber_sovereignty/',
'07_member_integration/',
'08_operational/',
'09_intelligence_security/',
'10_diplomatic_treaty/',
'11_technical_specs/',
'12_compliance_audit/',
'13_emergency_contingency/',
'csp_1113/',
'gru_reserve_system/',
'onboarding_package/',
'visual_assets/',
'formatted_book/',
]
def fix_links_in_file(file_path, project_root):
"""Fix links in a single file."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
original_content = content
file_dir = os.path.dirname(file_path)
rel_file_dir = os.path.relpath(file_dir, project_root)
# Only fix files in subdirectories (not root)
if rel_file_dir == '.':
return False
# Calculate how many ../ needed
depth = len(rel_file_dir.split(os.sep))
prefix = '../' * depth
# Fix references to root-level files
for root_file in ROOT_FILES:
# Pattern: [text](filename.md) or [text](./filename.md)
patterns = [
(r'(\[([^\]]+)\]\(\.?/)' + re.escape(root_file) + r'\))', f'\\1{prefix}{root_file}'),
(r'(\[([^\]]+)\]\(\.?/)' + re.escape(root_file) + r'#([^)]+)\))', f'\\1{prefix}{root_file}#\\3'),
(r'(\[([^\]]+)\]\(\.?/)' + re.escape(root_file) + r'\))', f'\\1{prefix}{root_file}'),
]
# Simple filename reference (not already with path)
simple_pattern = r'(\[([^\]]+)\]\(\.?/)' + re.escape(root_file) + r'([^)]*)\)'
def replace_simple(match):
link_text = match.group(2)
suffix = match.group(3) if match.group(3) else ''
return f'[{link_text}]({prefix}{root_file}{suffix})'
content = re.sub(simple_pattern, replace_simple, content)
# Also fix if it's just the filename without ./ or ../
pattern = r'(\[([^\]]+)\]\(\.?/)' + re.escape(root_file) + r'([^)]*)\)'
if not re.search(r'\.\.?/', pattern):
content = re.sub(r'(\[([^\]]+)\]\(\.?/)' + re.escape(root_file) + r'([^)]*)\)',
lambda m: f'[{m.group(2)}]({prefix}{root_file}{m.group(3)})', content)
# Fix directory references
for dir_ref in DIR_REFS:
# Pattern: [text](dirname/) or [text](./dirname/)
pattern = r'(\[([^\]]+)\]\(\.?/)' + re.escape(dir_ref) + r'([^)]*)\)'
def replace_dir(match):
link_text = match.group(2)
suffix = match.group(3) if match.group(3) else ''
return f'[{link_text}]({prefix}{dir_ref}{suffix})'
content = re.sub(pattern, replace_dir, content)
if content != original_content:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
return True
return False
except Exception as e:
print(f"Error processing {file_path}: {e}")
return False
def main():
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Find markdown files in subdirectories only
md_files = []
for root, dirs, files in os.walk(project_root):
# Skip .git and other hidden directories
dirs[:] = [d for d in dirs if d not in ['.git', 'node_modules', '__pycache__']]
# Skip root directory
if root == project_root:
continue
for file in files:
if file.endswith('.md'):
md_files.append(os.path.join(root, file))
print(f"Found {len(md_files)} markdown files in subdirectories")
print("Fixing references to root-level files...")
fixed_count = 0
for md_file in md_files:
if fix_links_in_file(md_file, project_root):
fixed_count += 1
print(f"Fixed: {os.path.relpath(md_file, project_root)}")
print(f"\nFixed {fixed_count} files")
if __name__ == '__main__':
main()