Skip to main content

scripts-fix-md001

#!/usr/bin/env python3 """

title: "MD001: Heading levels should only increment by one level at a time" component_type: script version: "1.0.0" audience: contributor status: stable summary: "import re from pathlib import Path" keywords: ['fix', 'md001'] tokens: ~500 created: 2025-12-22 updated: 2025-12-22 script_name: "fix-md001.py" language: python executable: true usage: "python3 scripts/fix-md001.py [options]" python_version: "3.10+" dependencies: [] modifies_files: false network_access: false requires_auth: false

"""

MD001: Heading levels should only increment by one level at a time

import re from pathlib import Path

def fix_md001(content): lines = content.split('\n') result = [] last_level = 0 fixed = 0

for line in lines:
if match := re.match(r'^(#{1,6})\s+', line):
level = len(match.group(1))
if level > last_level + 1:
# Fix: reduce to one level increment
correct_level = last_level + 1
result.append('#' * correct_level + line[level:])
fixed += 1
last_level = correct_level
else:
result.append(line)
last_level = level
else:
result.append(line)

return '\n'.join(result), fixed

def process_file(file_path, dry_run=False): try: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() fixed_content, count = fix_md001(content) if count > 0 and not dry_run: with open(file_path, 'w', encoding='utf-8') as f: f.write(fixed_content) return count except Exception as e: print(f"Error: {e}") return 0

if name == 'main': import argparse parser = argparse.ArgumentParser(description='Fix MD001') 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:
for md_file in Path(path_str).rglob('*.md'):
count = process_file(md_file, args.dry_run)
if count:
print(f"{'[DRY RUN] ' if args.dry_run else ''}Fixed {count} issues in {md_file}")
total += count
print(f"\nTotal: {total} issues fixed")