scripts-fix-md053-link-refs-needed
#!/usr/bin/env python3 """
title: "Fix Md053 Link Refs Needed" component_type: script version: "1.0.0" audience: contributor status: stable summary: "CODITECT Markdown Quality System Copyright © 2025 AZ1.AI INC - All Rights Reserved" from pat..." keywords: ['fix', 'link', 'md053', 'needed', 'refs'] tokens: ~500 created: 2025-12-22 updated: 2025-12-22 script_name: "fix-md053-link-refs-needed.py" language: python executable: true usage: "python3 scripts/fix-md053-link-refs-needed.py [options]" python_version: "3.10+" dependencies: [] modifies_files: false network_access: false requires_auth: false
CODITECT Markdown Quality System Copyright © 2025 AZ1.AI INC - All Rights Reserved""" from pathlib import Path import re
def fix_md053_link_refs_needed(content): """Remove link reference definitions that are not used.""" lines = content.split('\n') fixed = 0
# Find all reference link definitions: [label]: url
ref_defs = {}
for i, line in enumerate(lines):
match = re.match(r'^\[([^\]]+)\]:\s*(.+)', line)
if match:
label = match.group(1)
ref_defs[label] = i
# Find all reference link usages: [text][label] or [label][]
used_refs = set()
for line in lines:
# Match [text][ref] pattern
matches = re.findall(r'\[([^\]]+)\]\[([^\]]*)\]', line)
for match in matches:
ref = match[1] if match[1] else match[0]
used_refs.add(ref)
# Remove unused reference definitions
result = []
for i, line in enumerate(lines):
# Check if this line is an unused reference definition
is_unused_ref = False
for label, line_idx in ref_defs.items():
if i == line_idx and label not in used_refs:
is_unused_ref = True
fixed += 1
break
if not is_unused_ref:
result.append(line)
return '\n'.join(result), fixed
def process_file(file_path, dry_run=False): with open(file_path, 'r', encoding='utf-8') as f: content = f.read() fixed_content, count = fix_md053_link_refs_needed(content) if count > 0 and not dry_run: with open(file_path, 'w', encoding='utf-8') as f: f.write(fixed_content) return count
if name == 'main': import argparse parser = argparse.ArgumentParser() parser.add_argument('paths', nargs='*', default=['.']) parser.add_argument('--dry-run', action='store_true') args = parser.parse_args()
total = 0
for path_str in args.paths:
path = Path(path_str)
if path.is_file() and path.suffix == '.md':
count = process_file(path, args.dry_run)
if count:
print(f"{'[DRY RUN] ' if args.dry_run else ''}Fixed {count} in {path}")
total += count
elif path.is_dir():
for md_file in path.rglob('*.md'):
count = process_file(md_file, args.dry_run)
if count:
print(f"{'[DRY RUN] ' if args.dry_run else ''}Fixed {count} in {md_file}")
total += count
print(f"\nTotal: {total} fixed")