-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat_qmd.py
More file actions
147 lines (120 loc) · 4.82 KB
/
Copy pathformat_qmd.py
File metadata and controls
147 lines (120 loc) · 4.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#!/usr/bin/env python3
"""
QMD File Formatter - Ensures consistent formatting across all QMD files
"""
import os
import re
from pathlib import Path
def format_qmd_content(content):
"""Format QMD content for consistency"""
lines = content.split('\n')
formatted_lines = []
in_yaml_front_matter = False
in_code_block = False
yaml_delimiter_count = 0
for i, line in enumerate(lines):
# Track YAML front matter
if line.strip() == '---':
yaml_delimiter_count += 1
if yaml_delimiter_count <= 2:
in_yaml_front_matter = (yaml_delimiter_count == 1)
# Track code blocks
if line.strip().startswith('```'):
in_code_block = not in_code_block
# Skip formatting inside code blocks
if in_code_block:
formatted_lines.append(line)
continue
# Skip formatting inside YAML front matter
if in_yaml_front_matter:
formatted_lines.append(line)
continue
# Remove trailing whitespace
line = line.rstrip()
# Format headers - ensure space after #
if line.startswith('#') and not line.startswith('####'):
# Count the number of # characters
hash_count = 0
for char in line:
if char == '#':
hash_count += 1
else:
break
# Extract title after #
title = line[hash_count:].strip()
if title:
line = '#' * hash_count + ' ' + title
# Add blank line before headers (except first line and if previous line is already blank)
if (line.startswith('#') and
i > 0 and
formatted_lines and
formatted_lines[-1].strip() != '' and
not formatted_lines[-1].startswith('#')):
formatted_lines.append('')
# Add blank line after headers (if next line isn't blank and isn't another header)
should_add_blank_after_header = False
if line.startswith('#') and i < len(lines) - 1:
next_line = lines[i + 1].strip()
if next_line != '' and not next_line.startswith('#'):
should_add_blank_after_header = True
formatted_lines.append(line)
if should_add_blank_after_header:
# Check if next line will be blank
if i < len(lines) - 1 and lines[i + 1].strip() != '':
formatted_lines.append('')
# Format bullet points - ensure consistent spacing
if line.strip().startswith('- ') or line.strip().startswith('* '):
# Ensure single space after bullet
stripped = line.strip()
if stripped.startswith('- '):
content_after_bullet = stripped[2:]
else: # starts with '* '
content_after_bullet = stripped[2:]
# Count leading spaces for indentation
leading_spaces = len(line) - len(line.lstrip())
formatted_lines[-1] = ' ' * leading_spaces + '- ' + content_after_bullet
# Remove excessive blank lines (more than 2 consecutive)
final_lines = []
blank_count = 0
for line in formatted_lines:
if line.strip() == '':
blank_count += 1
if blank_count <= 2:
final_lines.append(line)
else:
blank_count = 0
final_lines.append(line)
# Ensure file ends with single newline
while final_lines and final_lines[-1] == '':
final_lines.pop()
return '\n'.join(final_lines) + '\n'
def format_qmd_file(file_path):
"""Format a single QMD file"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
original_content = f.read()
formatted_content = format_qmd_content(original_content)
# Only write if content changed
if formatted_content != original_content:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(formatted_content)
return True
return False
except Exception as e:
print(f"Error formatting {file_path}: {e}")
return False
def main():
"""Format all QMD files in the repository"""
base_path = Path('/home/ryuichi/dev/python-tutorial')
qmd_files = list(base_path.glob('**/*.qmd'))
print(f"Found {len(qmd_files)} QMD files to format")
formatted_count = 0
for qmd_file in qmd_files:
if format_qmd_file(qmd_file):
print(f"Formatted: {qmd_file}")
formatted_count += 1
else:
print(f"No changes: {qmd_file}")
print(f"\nFormatting complete! {formatted_count} files were updated.")
if __name__ == '__main__':
main()